How to implement an efficient infinite generator of prime numbers in Python?

后端 未结 13 2242
醉酒成梦
醉酒成梦 2020-11-22 01:50

This is not a homework, I am just curious.

INFINITE is the key word here.

I wish to use it as for p in primes(). I believe that this is a built-

13条回答
  •  迷失自我
    2020-11-22 02:37

    This isn't originally my code, however, it's worth posting. The original can be found here: http://code.activestate.com/recipes/117119/

    def gen_primes():
      D = {}
      q = 2  # first integer to test for primality.
    
      while True:
        if q not in D:
          # not marked composite, must be prime  
          yield q 
    
          #first multiple of q not already marked
          D[q * q] = [q] 
        else:
          for p in D[q]:
            D.setdefault(p + q, []).append(p)
          # no longer need D[q], free memory
          del D[q]
    
        q += 1
    

    It's a generator, so use it like any other.

    primes = gen_primes()
    for p in primes:
      print p
    

    It takes 1.62s to generate and put into a set, 1 million primes, on my desktop.

提交回复
热议问题