Sieve of Eratosthenes

Finds all primes up to N by iteratively crossing out multiples. Still the benchmark for prime generation in cryptography setup and competitive programming. Mark 2..N as prime; for p from 2 to sqrt(N), if p unmarked, cross out multiples of p.

Method

• List 2..N. • Take smallest uncrossed p, keep it. • Cross out p^2, p^2+p, ... • Repeat to sqrt(N). Survivors are prime.

Limitations

Memory grows with N; segmented sieve fixes this for huge N.

Example

Primes to 30: 2,3,5,7,11,13,17,19,23,29.

Sources

Educational reference only, not professional advice.

All algorithms