I go through prime generation in python using an Eratosthenes sieve and solutions that people advertise as a relatively quick option, for example, in a few of the answers to the question about optimizing prime generation in python is not simple, and the simple implementation that I am here competes with with them in efficiency. My implementation is below
def sieve_for_primes_to(n):
size = n//2
sieve = [1]*size
limit = int(n**0.5)
for i in range(1,limit):
if sieve[i]:
val = 2*i+1
tmp = ((size-1) - i)//val
sieve[i+val::val] = [0]*tmp
return sieve
print [2] + [i*2+1 for i, v in enumerate(sieve_for_primes_to(10000000)) if v and i>0]
Refund deadlines
python -m timeit -n10 -s "import euler" "euler.sieve_for_primes_to(1000000)"
10 loops, best of 3: 19.5 msec per loop
While the method described in the answer to the above related question, as the fastest of the cookbook on peony, is given below.
import itertools
def erat2( ):
D = { }
yield 2
for q in itertools.islice(itertools.count(3), 0, None, 2):
p = D.pop(q, None)
if p is None:
D[q*q] = q
yield q
else:
x = p + q
while x in D or not (x&1):
x += p
D[x] = p
def get_primes_erat(n):
return list(itertools.takewhile(lambda p: p<n, erat2()))
At startup, it gives
python -m timeit -n10 -s "import euler" "euler.get_primes_erat(1000000)"
10 loops, best of 3: 697 msec per loop
My question is: why do people advertise the above from a cook’s book, which is relatively complex as an ideal primary generator?
cobie