Fast clean numerical sieve in Python

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?

+5
2

, script @unutbu N :

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 [2] + [i*2+1 for i, v in enumerate(sieve) if v and i>0]

MBPro i7 script < 1000000, 1,5 rwh_primes2, rwh_primes1 (1.2), rwh_primes (1.19) primeSieveSeq (1.12) (@andreasbriese ).

+8

"" . 10 20 ,

...
print(len( [2] + [i*2+1 for i, v in 
  enumerate(sieve_for_primes_to(10000000)) if v and i>0]))

, 664579 1270607 ,

...
print( list( islice( (p for p in postponed_sieve() ), n-1, n+1))) 

, " 3.1x... 3.3x .:) 36x , - .

, - - , "" , . - , , .

, , , ~ n^(1+a), a < 0.1...0.2 , . ~ n^1.5 ~ n^2 .

+3

All Articles