#356 · Iterators and generators · Advanced · 125 XP · about 25 min
Write a generator primes() that yields the prime numbers in order, 2, 3, 5, 7, 11 and so on, forever. Each call to primes() starts a new sequence from 2.
The sieve of Eratosthenes is fast, but it needs to know in advance how far to go, and this generator never knows when it will be stopped. Find a way to keep the sieve's speed without a limit.
from itertools import islice list(islice(primes(), 10)) # returns [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] next(islice(primes(), 9999, None)) # returns 104729, the 10,000th prime g = primes() next(g), next(g), next(g) # (2, 3, 5)
First solves only, ranked by stars and then time.