import itertools
import math
def primes():
yield 2
n = 3
p = []
while True:
# --------- this is exhaustive trial division -------------------
# testing needlessly by all preceding primes
# -- this confirms O'Neill's complexity for Turner's sieve - *BUT* NB!
# *BUT* in an IMPERATVE setting of Python;
# in Haskell for bigger n's it's WORSE than n^2 --
# the operational overhead trumps over the calculational one
# (which is the ONLY thing that she took into account)
#if not any( n % f == 0 for f in p ): # 2k: 1.02s-5.9MB 7k:12.59s-5.9MB
# n^2.01
#if not any( n % f == 0 for f in p if f*f <= n ): # 2k: 0.58s-5.9MB 10k:14.43s-6.2MB
# # n^2.00
# -------- this is optimal trial division - one-by-one generation -------------
# - refetching primes to test by anew for each new candidate
if not any( n % f == 0 for f in
itertools.takewhile(lambda f: f*f <= n, p) ): # 10k: 0.80s-5.9MB 50k: 7.22s-5.9MB
yield n # n^1.37
p.append( n )
n += 2
# ------------ this is optimal trial division - segmented generation, ----------------
# prefetching primes prefixes to test by once for each segment between primes squares
def pprimes(): # 10k: 0.41s-6.2MB 50k:3.57s-5.9MB 100k:9.42s-5.9MB !+++++++
yield 2 # n^1.34 n^1.40
k = 0; p = [];
n = 3; q = 9;
while True:
ps = p[:k]
xs = itertools.filterfalse( lambda x: any( x % f == 0 for f in ps ),
range(n,q,2) )
for x in xs:
yield x
p.append( x )
n = q+2; k += 1; q = p[k]*p[k]
# ------------ this is code from Wikipedia Sieve of Eratosthenes page ---------------
def eratosthenes_sieve(n): # 10k: 0.05s-6.2MB 100k:0.57s-6.7MB 500k:3.72s-6.7MB 1m:MEMOUT
# n^1.05 n^1.17
m = n*math.ceil( math.log(n)*1.1 ) # 10k:*11 100k:*13 1m:*16
candidates = list(range(m+1))
fin = int(m**0.5)
for i in range(2, fin+1):
if candidates[i]:
candidates[2*i::i] = [None] * len(candidates[2*i::i])
# Filter out non-primes and return the list.
return [i for i in candidates[2:] if i]
n=10000; print( eratosthenes_sieve(n)[n-10:n] )
#n=10000; print( list( itertools.islice( pprimes(), n-5, n)))
#print( list( itertools.islice( pprimes(), 10)))