I need to generate prime numbers using generator in Python. Here is my code:
def genPrimes():
yield 2
x=2
while True:
x+=1
for p in genPrimes():
if (x%p)==0:
break
else:
yield x
I have a RuntimeError: maximum recursion depth exceeded after the 2nd prime.next() when I run it.
The fastest way to generate primes is with a sieve. Here we use a segmented Sieve of Eratosthenes to generate the primes, one by one with no maximum, in order;
ps
is the list of sieving primes less than the current maximum andqs
is the offset of the smallest multiple of the correspondingps
in the current segment.A simple
isPrime
using trial division is sufficient, since it will be limited to the fourth root of n. The segment size2 * delta
is arbitrarily set to 100000. This method requires O(sqrt n) space for the sieving primes plus constant space for the sieve.It is slower but saves space to generate candidate primes with a wheel and test the candidates for primality with an
isPrime
based on strong pseudoprime tests to bases 2, 7, and 61; this is valid to 2^32.If you're interested in programming with prime numbers, I modestly recommend this essay at my blog.