Sieve of Eratosthenes
Intermediate · 8 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
The Sieve of Eratosthenes finds every prime up to a limit by crossing out multiples. Start with 2 and cross out its multiples, then the next uncrossed number, and so on. Survivors are primes. It is the fastest simple way to prepare a whole table of primes.
Practical use cases
- Web app: Preparing table sizes for a cache. An app wants to choose the nearest prime slot count above the expected number of cached items. Rather than testing each candidate separately, it builds a sieve of primes up to a million once when the server boots. Afterwards, picking a good prime is a single lookup.
- Web app: Coding challenge platform. A practice site for students has 500 problems that ask whether numbers are prime. Testing each number separately for 100,000 queries is slow. Running the sieve once up to the largest number gives instant yes or no answers to every query afterwards.
- System: Fast factorising of many numbers. A variation stores the smallest prime factor of every number up to a limit. Software that must split thousands of numbers into prime factors, for example in cryptography research, then peels them apart in a few steps each, instead of trying every divisor again from scratch for every number.
The story: The Sieve at the Flour Mill
At the village flour mill, Zoya watched the miller shake wheat flour through a sieve. The fine flour fell through and the stones and husks stayed behind. "What if I could shake numbers through a sieve," she wondered, "and let only the primes remain?"
She wrote the numbers 1 to 30 on a long strip. She struck out 1. Then she circled 2, which must be prime, and struck out every second number after it: 4, 6, 8... all the multiples of 2. The next un-struck number was 3. Circle it, and strike out its multiples: 9, 12, 15... Then 5. The strip filled with crosses, and the circled numbers were primes.
"Why start striking at 3 × 3 = 9, not 6?" Kabir asked. "Because 6 is a multiple of 2, and 2 already crossed it out," said Zoya. "And we can stop when p × p goes past 30. Everything left is guaranteed prime."
This method is over two thousand years old, named after Eratosthenes, the Greek librarian who also measured the Earth. It finds every prime up to a limit in one sweep, far faster than testing each number alone. It is the first tool you reach for when a problem says "all primes up to a million".
How to spot this problem, and where you need it
You need many primes, or answers about many numbers being prime, and testing each number one by one is making your code or your page too slow.
Signs you need it
- You must list all primes below a limit such as 100,000 or 10 million.
- The same is-it-prime question is asked again and again for different numbers within a known range.
- A for-loop calls an is_prime() function inside another loop, and the whole thing is crawling.
Where to use it in a project
- Start-up scripts that precompute a lookup table of primes for hashing, scheduling or game logic.
- Back-ends of contests, quizzes and maths-learning sites that answer thousands of prime queries per minute.
The solution
Make an array of flags, one per number up to your limit, all marked as maybe prime. Starting at 2, find the next number still marked, and mark all its multiples as not prime, beginning from its square. Repeat until you pass the square root of the limit. Whatever is still marked is prime. Keep the array in memory and answer queries by looking at one flag.
Payoff: Before: testing each number separately for primes up to a million takes a long time. After: one sieve pass finishes in a fraction of a second.
Explain it like I am 8
Write the numbers in a row. Cross out all the multiples of 2, then all the multiples of 3, then 5, and so on. Whatever is not crossed out when you finish is a prime. It is like a sieve that only lets the special numbers stay.
How it works, step by step
- List the numbers 2 to n and treat all of them as "maybe prime".
- Take the next number p still marked as prime.
- Strike out its multiples, starting at
p * p, stepping by p. - Stop when
p * pgoes past n. - Collect the survivors. Every number still marked is prime.
The code in four languages
PHP
<?php
// Return all primes up to $n using the sieve of Eratosthenes.
function sieve(int $n): array {
$isPrime = array_fill(0, $n + 1, true);
$isPrime[0] = false;
if ($n >= 1) $isPrime[1] = false;
for ($p = 2; $p * $p <= $n; $p++) {
if (!$isPrime[$p]) continue;
for ($m = $p * $p; $m <= $n; $m += $p) { // strike out multiples
$isPrime[$m] = false;
}
}
$primes = [];
foreach ($isPrime as $num => $ok) {
if ($ok) $primes[] = $num;
}
return $primes;
}
echo "Primes up to 30: " . implode(', ', sieve(30)) . "
";
echo "How many primes below 100? " . count(sieve(100)) . "
"; // 25
echo "How many primes below 100000? " . count(sieve(100000)) . "
";JavaScript
// Return all primes up to n using the sieve of Eratosthenes.
function sieve(n) {
const isPrime = new Array(n + 1).fill(true);
isPrime[0] = false;
if (n >= 1) isPrime[1] = false;
for (let p = 2; p * p <= n; p++) {
if (!isPrime[p]) continue;
for (let m = p * p; m <= n; m += p) { // strike out multiples
isPrime[m] = false;
}
}
const primes = [];
for (let num = 0; num <= n; num++) {
if (isPrime[num]) primes.push(num);
}
return primes;
}
console.log("Primes up to 30: " + sieve(30).join(', '));
console.log("How many primes below 100? " + sieve(100).length); // 25
console.log("How many primes below 100000? " + sieve(100000).length);Java
import java.util.*;
public class Main {
// Return all primes up to n using the sieve of Eratosthenes.
static List<Integer> sieve(int n) {
boolean[] isPrime = new boolean[n + 1];
Arrays.fill(isPrime, true);
isPrime[0] = false;
if (n >= 1) isPrime[1] = false;
for (int p = 2; p * p <= n; p++) {
if (!isPrime[p]) continue;
for (int m = p * p; m <= n; m += p) { // strike out multiples
isPrime[m] = false;
}
}
List<Integer> primes = new ArrayList<>();
for (int num = 0; num <= n; num++) {
if (isPrime[num]) primes.add(num);
}
return primes;
}
public static void main(String[] args) {
System.out.println("Primes up to 30: " + sieve(30).toString().replaceAll("[\\[\\]]", ""));
System.out.println("How many primes below 100? " + sieve(100).size()); // 25
System.out.println("How many primes below 100000? " + sieve(100000).size());
}
}Go
package main
import (
"fmt"
"strconv"
"strings"
)
// sieve returns all primes up to n using the sieve of Eratosthenes.
func sieve(n int) []int {
isPrime := make([]bool, n+1)
for i := range isPrime {
isPrime[i] = true
}
isPrime[0] = false
if n >= 1 {
isPrime[1] = false
}
for p := 2; p*p <= n; p++ {
if !isPrime[p] {
continue
}
for m := p * p; m <= n; m += p { // strike out multiples
isPrime[m] = false
}
}
var primes []int
for num, ok := range isPrime {
if ok {
primes = append(primes, num)
}
}
return primes
}
func main() {
var shown []string
for _, p := range sieve(30) {
shown = append(shown, strconv.Itoa(p))
}
fmt.Println("Primes up to 30:", strings.Join(shown, ", "))
fmt.Println("How many primes below 100?", len(sieve(100))) // 25
fmt.Println("How many primes below 100000?", len(sieve(100000)))
}Time: O(n log log n) · Extra space: O(n). Each number is struck only a handful of times, so the whole sieve is just a little slower than one pass over n numbers.
Watch out for
- Starting the strike-out from
2 * pinstead ofp * p. Correct but wasteful. - Forgetting to mark 0 and 1 as non-prime, so they leak into the result.
- Using the sieve for a single number. For one number, trial division up to the square root is simpler and lighter on memory.
Quick check
- After the sieve finishes, which numbers are prime?
- The ones struck out
- The ones never struck out (2 and above)
- Only odd numbers
- For the prime p, where do we start striking out?
- p × p
- 2
- p + 1
- When can the outer loop stop?
- When p reaches n
- When p × p is bigger than n
- After the first prime