fork(2) download
  1. # from: http://r...content-available-to-author-only...e.org/wiki/Sieve_of_Eratosthenes#Infinite_generator_with_a_faster_algorithm
  2.  
  3. def primes():
  4. yield 2; yield 3; yield 5; yield 7;
  5. bps = (p for p in primes()) # additional primes supply
  6. p = next(bps) and next(bps) # discard 2, then get 3
  7. q = p * p # 9 - square of next prime to be put
  8. sieve = {} # into sieve dict
  9. n = 9 # the initial candidate number
  10. while True:
  11. if n not in sieve: # is not a multiple of previously recorded primes
  12. if n < q:
  13. yield n # n is prime
  14. else:
  15. p2 = p + p # n == p * p: for prime p, add p * p + 2 * p,
  16. sieve[q + p2] = p2 # with 2 * p as incremental step
  17. p = next(bps); q = p * p # advance base prime and next prime to be put
  18. else:
  19. s = sieve.pop(n); nxt = n + s # n is composite, advance
  20. while nxt in sieve: nxt += s # ensure each entry is unique
  21. sieve[nxt] = s # next non-marked multiple of this prime
  22. n += 2 # work on odds only
  23.  
  24. ps = primes() # 100k: 0.52s-7.9MB
  25. for n in xrange(1, 1000000): next(ps) # 200k: 1.12s-7.9MB n^1.11 !!
  26. print next(ps) # 400k: 2.39s-7.9MB n^1.09 !!!
  27. # 1m: 6.01s-7.9MB n^1.10 !!! 15485863
Success #stdin #stdout 6.36s 7852KB
stdin
Standard input is empty
stdout
15485863