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

后端 未结 13 2502
醉酒成梦
醉酒成梦 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:33

    Here's a generator that's a little truer to how it's done in Haskell: filtering against composites of known primes, then adding the remaining primes to the list.

    def gen_primes():
        primes = []
        i = 2
        while True:
            prime = True
            for p in primes:
                if not (i % p):
                    prime = False
                    break
            if prime:
                yield i
                primes.append(i)
            i += 1
    

提交回复
热议问题