fork download
  1. def primegen():
  2. """'Infinite' prime generator - a litte slow
  3. about 7.4 sec for 10^6 primes
  4. 90 sec for 10^7 primes
  5. """
  6. yield from (2,3)
  7. blocked = {}
  8. ps = primegen()
  9. candidate = prime = next(ps) and next(ps)
  10. prime_squared = prime * prime
  11. while True:
  12. candidate += 2
  13. if candidate in blocked:
  14. step = blocked.pop(candidate)
  15. elif candidate == prime_squared:
  16. step = prime + prime
  17. prime = next(ps)
  18. prime_squared = prime * prime
  19. else:
  20. yield candidate
  21. continue
  22. m = candidate + step
  23. while m in blocked:
  24. m += step
  25. blocked[m] = step
  26.  
  27. p = primegen()
  28. for i in range(10):
  29. print(next(p))
  30.  
Success #stdin #stdout 0.02s 9944KB
stdin
Standard input is empty
stdout
2
3
5
7
11
13
17
19
23
29