fork(1) download
  1. # incremental sieve of eratosthenes
  2.  
  3. def primegen(): # http://stackoverflow.com/a/20660551
  4. yield 2; yield 3 # prime (!) the pump
  5. ps = primegen() # sieving primes
  6. p = next(ps) and next(ps) # first sieving prime
  7. D, q, c = {}, p*p, p # initialize
  8. def add(m, s): # insert multiple/stride
  9. while m in D: m += s # find unused multiple
  10. D[m] = s # save multiple/stride
  11. while True: # infinite list
  12. c += 2 # next odd candidate
  13. if c in D: # c is composite
  14. s = D.pop(c) # fetch stride
  15. add(c+s, s) # add next multiple
  16. elif c < q: yield c # c is prime; yield it
  17. else: # (c == q) # add sqrt(c) to sieve
  18. add(c+p+p, p+p) # insert in sieve
  19. p = next(ps) # next sieving prime
  20. q = p * p # ... and its square
  21.  
  22. ps = primegen()
  23. for i in range(10000):
  24. p = next(ps)
  25. print p
Success #stdin #stdout 0.06s 9120KB
stdin
Standard input is empty
stdout
104729