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

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

    And another answer, more memory-efficient than my erat3 answer here:

    import heapq
    
    def heapprimegen():
        hp= []
        yield 2
        yield 3
        cn= 3
        nn, inc= 3, 6
        while 1:
            while cn < nn:
                yield cn
                heapq.heappush(hp, (3*cn, 2*cn))
                cn+= 2
            cn= nn+2
            nn, inc= heapq.heappushpop(hp, (nn+inc, inc))
    

    It maintains a heap (a list) of prime multiples rather than a dictionary. It loses some speed, obviously.

提交回复
热议问题