简体   繁体   中英

Generating infinite prime number squence using generators

I am trying to generate an infinite prime number sequence using sieve of 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?

If you're satisfied with successive division checks, you can implement the more common version:

  • Initialize your sequence with 2
  • Starting with 3 and checking only odd numbers ...
  • If N isn't divisible by any existing prime,
  • ... add it to the list of primes and emit it.
  • increment N by 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.

Stepping through one step at a time:

while True:
    n = next(N)

n is 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 . Note that we said multiples of n , not multiples of 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. So we assign 3 to n and yield it. 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.

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. Then we do the modulus again and get the same result. So we assign 4 to n and yield it...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM