fork(1) download
  1. def primes(): # http://r...content-available-to-author-only...e.org/wiki/Sieve_of_Eratosthenes
  2. for x in [2,3,5,7]: yield x # #Infinite_generator_with_a_faster_algorithm
  3. ps = (p for p in primes()) # additional primes supply
  4. p = ps.next() and ps.next() # discard 2, then get 3
  5. q = p*p # 9 - square of next prime to be put
  6. sieve = {} # into sieve dict
  7. n = 9 # the candidate number
  8. while True:
  9. if n not in sieve: # is not a multiple of previously recorded primes
  10. if n < q: # n is prime
  11. yield n
  12. else:
  13. add(sieve, q + 2*p, 2*p) # n==p*p: for prime p, under p*p + 2*p,
  14. p = ps.next() # add 2*p as incremental step
  15. q = p*p
  16. else:
  17. s = sieve.pop(n)
  18. add(sieve, n + s, s)
  19. n += 2 # work on odds only
  20.  
  21. def add(sieve,next,step):
  22. while next in sieve: # ensure each entry is unique
  23. next += step
  24. sieve[next] = step # next non-marked multiple of a prime
  25.  
  26. def test(): # 100k: 0.73s-4.7MB
  27. ps = primes() # 200k: 1.55s-4.7MB n^1.09 !!
  28. for i in xrange(1,1000000): ps.next() # 400k: 3.28s-4.7MB n^1.08 !!!
  29. print ps.next() # 1m: 8.86s-4.7MB n^1.08 !!! 15485863
  30.  
  31. test()
Success #stdin #stdout 8.72s 4676KB
stdin
Standard input is empty
stdout
15485863