[英]How to implement an efficient infinite generator of prime numbers in Python?
[英]How to make an infinite generator in python to all prime numbers?
我试图在 python 中制作这个无限生成器:
import math
def all_primes():
count = 3
while True:
flag = True
for x in range(2, int(math.sqrt(count) + 1)):
if count % x == 0:
flag = False
if flag:
yield count
else:
count += 1
print("Aumentou count ", count)
for i in all_primes():
print(i)
但在 output 中,它总是给我 3。这是为什么呢?
找到素数后不会增加计数,因此您总是返回相同的值 (3)。
随着您的前进,您的素数生成器将在每个素数之间花费越来越长的时间。
这是一个更有效的无限素数生成器。 它的灵感来自 Eratosthenes 的筛子,但使用字典仅在到达非质数时传播倍数,并将质数移动到下一个尚未标记为非质数的倍数:
def genPrimes():
yield 2 # get the first prime out of the way
N,skips = 1,dict() # skips is {PrimeMultiple:2xPrime}
while True:
N += 2 # next prime candidate
if N not in skips: # N is prime (i.e. not multiple of a prime)
yield N # return it
skips[N*N] = 2*N # setup its skipping entry
else:
stride = skips.pop(N) # number to skip (i.e. not prime)
multiple = N + stride # advance skip to next multiple
while multiple in skips: # not already skipped
multiple += stride
skips[multiple] = stride
输出:
for p in genPrimes(): print(p)
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
...
到目前为止,skips 字典中每个素数仅包含一个条目,并且不需要预先分配 memory。 这种方法以空间换取时间。
您的代码始终产生“3”的原因是“标志”始终为真。 使用 int(math.sqrt(count)+1) 在 for 循环中进行数学运算使得循环仅从 2 -> 2 开始。所以唯一检查的是如果 3 % 2 == 0 永远不会为真. 因此 flag 始终为 false 并且计数永远不会增加。
那是因为 for 循环从不迭代。 如果 count=3 则int(math.sqrt(count) + 1)
将返回 2,因此 for 循环的范围将是 (2,2),因此它永远不会迭代,并且标志值不会改变,因此计数值总是相同的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.