栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Python中的简单Prime生成器

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python中的简单Prime生成器

有一些问题:

  • 当计数不除以x时,为什么要打印计数?这并不意味着它是素数,仅意味着该特定x不会将其除
  • continue
    移至下一个循环迭代-但你确实想使用停止它
    break

    这是你的代码,其中包含一些修复程序,它仅输出质数:
import mathdef main():    count = 3    while True:        isprime = True        for x in range(2, int(math.sqrt(count) + 1)): if count % x == 0:      isprime = False     break        if isprime: print count        count += 1

有关更有效的质子生成,请参见其他人的建议,参见戊二烯筛。这是一个不错的,经过优化的实现,带有很多注释:

# Sieve of Eratosthenes# Code by David Eppstein, UC Irvine, 28 Feb 2002# http://pre.activestate.com/recipes/117119/def gen_primes():    """ Generate an infinite sequence of prime numbers.    """    # Maps composites to primes witnessing their compositeness.    # This is memory efficient, as the sieve is not "run forward"    # indefinitely, but only as long as required by the current    # number being tested.    #    D = {}    # The running integer that's checked for primeness    q = 2    while True:        if q not in D: # q is a new prime. # Yield it and mark its first multiple that isn't # already marked in previous iterations #  yield q D[q * q] = [q]        else: # q is composite. D[q] is the list of primes that # divide it. Since we've reached q, we no longer # need it in the map, but we'll mark the next  # multiples of its witnesses to prepare for larger # numbers #  for p in D[q]:     D.setdefault(p + q, []).append(p) del D[q]        q += 1

请注意,它返回一个生成器。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/596704.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号