Sieve of Eratosthenes
Math / Number Theory O(n log log n) O(n)Finds every prime up to n by crossing out the multiples of each prime, starting from its square.
n
1/67
Assume every number from 2 to 60 is prime.
InvariantEvery number still uncrossed below p² has no factor ≤ p, so it is prime.
sieve-of-eratosthenes.c
void sieve(int n) {int prime[n + 1];for (int i = 0; i <= n; i++) prime[i] = 1;prime[0] = prime[1] = 0;for (int p = 2; p * p <= n; p++) {if (!prime[p]) continue;for (int m = p * p; m <= n; m += p)prime[m] = 0; /* cross out multiple */}for (int i = 2; i <= n; i++)if (prime[i]) printf("%d ", i);}
How Sieve of Eratosthenes works
List 2..n; repeatedly take the next surviving number (a prime) and cross out its multiples starting at p². Anything still standing at the end was never a multiple of a smaller prime.
When to use it
Generating all primes up to n, smallest-prime-factor tables for fast factorization.