2025-04-24
The Sieve of Eratosthenes is a simple and efficient algorithm used to find all prime numbers up to a certain number `n`. It was invented over 2,000 years ago by the Greek mathematician Eratosthenes. Despite its age, it’s still one of the fastest ways to generate a list of primes up to a limit.
Imagine you have a list of numbers from 2 to `n`. The Sieve works by eliminating the multiples of each prime number starting from 2.
Result: The numbers that remain unmarked are prime.
Start with this list: [2, 3, 4, 5, 6, ..., 30]
Result: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
public class Sieve {
public static void main(String[] args) {
int n = 30;
boolean[] isPrime = new boolean[n + 1];
// Assume all numbers are prime
for (int i = 2; i <= n; i++) {
isPrime[i] = true;
}
for (int p = 2; p * p <= n; p++) {
if (isPrime[p]) {
for (int i = p * p; i <= n; i += p) {
isPrime[i] = false;
}
}
}
// Print prime numbers
for (int i = 2; i <= n; i++) {
if (isPrime[i]) {
System.out.print(i + " ");
}
}
}
}
You eliminate non-primes in batches (multiples). It runs in O(n log log n) time, which is fast for large `n`.
Use the Sieve when:
That’s it! Simple, fast, and elegant.