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

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

    For posterity, here's a rewrite of Will Ness's beautiful algorithm for Python 3. Some changes are needed (iterators no longer have .next() methods, but there's a new next() builtin function). Other changes are for fun (using the new yield from replaces four yield statements in the original. More are for readability (I'm not a fan of overusing ;-) 1-letter variable names).

    It's significantly faster than the original, but not for algorithmic reasons. The speedup is mostly due to removing the original's add() function, doing that inline instead.

    def psieve():
        import itertools
        yield from (2, 3, 5, 7)
        D = {}
        ps = psieve()
        next(ps)
        p = next(ps)
        assert p == 3
        psq = p*p
        for i in itertools.count(9, 2):
            if i in D:      # composite
                step = D.pop(i)
            elif i < psq:   # prime
                yield i
                continue
            else:           # composite, = p*p
                assert i == psq
                step = 2*p
                p = next(ps)
                psq = p*p
            i += step
            while i in D:
                i += step
            D[i] = step
    

提交回复
热议问题