[英]Generating infinite prime number squence using generators
I am trying to generate an infinite prime number sequence using sieve of Eratosthenes. 我正在尝试使用Eratosthenes筛子生成无限质数序列。 This is the code:
这是代码:
def naturals()->int:
'''Generate natural numbers indefinitely'''
i = 1
while True:
yield i
i = i+1
def primes():
N = naturals()
_ = next(N)#Pop out 1
while True:
n = next(N)
yield n
N = (i for i in N if i%n != 0)
However, the generator above simply yields 2,3,4... So where exactly did I go wrong? 但是,上面的生成器仅产生2,3,4 ...那么我到底在哪里出错?
If you're satisfied with successive division checks, you can implement the more common version: 如果您对后续的划分检查感到满意,则可以实施更通用的版本:
N
isn't divisible by any existing prime, N
无法被任何现有素数整除, N
by 2. N
增加2。 Code in your styling: 样式中的代码:
def primes():
sofar = [2]
n = 3
yield 2
while True:
if all(n%i for i in sofar):
sofar.append(n)
yield n
n += 2
This slows down to 100 primes / sec around N = 250,000 and continues to degrade from there. 在N = 250,000附近,速度减慢至100灌注/秒,并从那里继续退化。
Stepping through one step at a time: 一次完成一个步骤:
while True:
n = next(N)
n
is 2. n
是2。
yield n
N = (i for i in N if i%n != 0)
This wraps N
in a generator which removes values that are multiples of n
. 这会将
N
包装在生成器中,该生成器将删除n
倍数的值。 Note that we said multiples of n
, not multiples of 2. 请注意,我们说的是
n
倍数,而不是2的倍数。
On the next loop, we grab the next element out of naturals()
, getting 3, modulus it against n
, which is 2, and get 1, which is not zero. 在下一个循环中,我们从
naturals()
中获取下一个元素,得到3,对n
模数化,得到2,得到1,但不为零。 So we assign 3 to n and yield it. 因此,我们将3分配给n并产生它。 We then wrap the previous
N
in another generator which does the same thing as the previous wrapper did, which slows it down but has no other effect. 然后,我们将前一个
N
包装到另一个生成器中,该生成器执行与前一个包装器相同的操作,这会降低它的速度,但没有其他作用。
Then, on the next loop, we grab the next element out of naturals()
, getting 4, modulus it against n
, which is 3, and get 1, which is not zero. 然后,在下一个循环中,我们从
naturals()
抓取下一个元素,将其对n
取3的模数为4,并得到1,而不为零。 Then we do the modulus again and get the same result. 然后,我们再次进行模量计算,得到相同的结果。 So we assign 4 to
n
and yield it... 所以我们给
n
赋4并产生它...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.