Editor

Endless Primes

#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.

Examples

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)

Constraints

  • The tests read up to the first 50,000 primes (the 50,000th is 611,953), so testing every possible divisor of every number is far too slow

Fastest solvers

Leaderboard

First solves only, ranked by stars and then time.