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

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

    Do a segmented sieve, where the size of a segment is determined by available memory or the maximal size of a bitset.

    For each segment represent the numbers in some interval [n; n + segment_size) as a bit set and sieve with all prime numbers below the square root of the upper bound.

    Using a bit set uses less memory than a hash table or tree data structure, because you are working with dense sets of numbers.

提交回复
热议问题