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

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

    Here is a simple but not terribly slow one using a heap instead of a dict:

    import heapq
    
    def heap_prime_gen_squares(): 
        yield 2  
        yield 3  
        h = [(9, 6)]
        n = 5
        while True:
            a, b = h[0]
            while n < a:
                yield n
                heapq.heappush(h, (n * n, n << 1))
                n += 2
            heapq.heapreplace(h, (a + b, b))  # Replace h[0], which is still (a, b).
    

    My speed measurements of user time for the first 1 million primes (smaller numbers are better):

    • postponed_sieve (dict-based): 8.553s
    • erat2b (dict-based): 9.513s
    • erat2a (dict-based): 10.313s
    • heap_prime_gen_smallmem (heap-based): 23.935s
    • heap_prime_gen_squares (heap-based): 27.302s
    • heapprimegen (dict-based): 145.029s

    So dict-based approaches seem to be the fastest.

提交回复
热议问题