Eratosties筛-寻找Python的Primes我只想澄清一点,这不是家庭作业的问题:)我想为我正在构建的数学应用程序找到素数&偶然发现的。埃拉托斯提尼筛接近。我已经用Python编写了它的实现。但速度太慢了。比方说,如果我想找到不到200万的素数。需要超过20分钟。(我在这一点上停止了它)。我怎么才能加快速度?def primes_sieve(limit):
limitn = limit+1
primes = range(2, limitn)
for i in primes:
factors = range(i, limitn, i)
for f in factors[1:]:
if f in primes:
primes.remove(f)
return primesprint primes_sieve(2000)最新情况:最后,我对这段代码进行了分析&发现在从列表中删除元素上花费了相当多的时间。考虑到它必须遍历整个列表(最坏的情况)来查找元素&然后删除它,然后重新调整列表,这是完全可以理解的(也许会有一些副本继续吗?)不管怎么说,我把字典的单子扔掉了。我的新计划-def primes_sieve1(limit):
limitn = limit+1
primes = dict()
for i in range(2, limitn): primes[i] = True
for i in primes:
factors = range(i,limitn, i)
for f in factors[1:]:
primes[f] = False
return [i for i in primes if primes[i]==True]print primes_sieve1(2000000)
3 回答
海绵宝宝撒
TA贡献1809条经验 获得超8个赞
primes_sieve
primes_sieve1
def primes_sieve2(limit): a = [True] * limit # Initialize the primality list a[0] = a[1] = False for (i, isprime) in enumerate(a): if isprime: yield i for n in range(i*i, limit, i): # Mark factors non-prime a[n] = False
i*i
慕姐8265434
TA贡献1813条经验 获得超2个赞
def eratosthenes(n): multiples = [] for i in range(2, n+1): if i not in multiples: print (i) for j in range(i*i, n+1, i): multiples.append(j)eratosthenes(100)
米脂
TA贡献1836条经验 获得超3个赞
def primes_sieve(limit): limitn = limit+1 not_prime = set() primes = [] for i in range(2, limitn): if i in not_prime: continue for f in range(i*2, limitn, i): not_prime.add(f) primes.append(i) return primesprint primes_sieve(1000000)
def primes_sieve(limit): limitn = limit+1 not_prime = [False] * limitn primes = [] for i in range(2, limitn): if not_prime[i]: continue for f in xrange(i*2, limitn, i): not_prime[f] = True primes.append(i) return primes
添加回答
举报
0/150
提交
取消