Sieve-of-eratosthenes
Problem link : Sieve-of-eratosthenes
Problem Statement
Given a positive integer n, return all prime numbers less than or equal to n using the Sieve of Eratosthenes algorithm.
A prime number is a number greater than 1 that is divisible only by 1 and itself.
Examples
Example 1:
-
Input:
n = 10 -
Output:
2 3 5 7 -
Explanation: These are all the prime numbers ≤ 10
Example 2:
-
Input:
n = 35 -
Output:
2 3 5 7 11 13 17 19 23 29 31 -
Explanation: These are the primes ≤ 35
Constraints
1 ≤ n ≤ 10⁴
Intuition
To check for primes individually up to n would require checking each number for divisibility — a time-consuming process.
Instead, the Sieve of Eratosthenes improves efficiency by:
-
Assuming all numbers from
2tonare prime. -
Iteratively marking the multiples of each prime as non-prime.
Approach
-
Create a boolean array
isPrime[]of sizen + 1, initialized totrue. -
Set
isPrime[0]andisPrime[1]tofalsesince0and1are not primes. -
Iterate
ifrom2to√n:- If
isPrime[i] == true, mark all multiples ofi(starting fromi*i) asfalse.
- If
-
After the loop, the indices in
isPrime[]which remaintrueare the prime numbers.
Java Code
import java.util.*;
class Solution {
static List<Integer> sieveOfEratosthenes(int n) {
boolean[] isPrime = new boolean[n + 1];
Arrays.fill(isPrime, true); // Assume all are prime initially
isPrime[0] = isPrime[1] = false;
for (int i = 2; i * i <= n; i++) {
if (isPrime[i]) {
// Mark all multiples of i as non-prime
for (int j = i * i; j <= n; j += i) {
isPrime[j] = false;
}
}
}
// Collect all primes
List<Integer> primes = new ArrayList<>();
for (int i = 2; i <= n; i++) {
if (isPrime[i]) {
primes.add(i);
}
}
return primes;
}
}
Dry Run
Input: n = 10
- Initial
isPrime[]=[false, false, true, true, true, true, true, true, true, true, true]
Step 1: i = 2
- Mark
4, 6, 8, 10asfalse
Step 2: i = 3
- Mark
9asfalse
Resulting Primes: 2, 3, 5, 7
Time Complexity
-
O(n log log n) — Efficient for generating primes up to
n -
Inner loop runs fewer times as
iincreases
Space Complexity
- O(n) — Due to boolean array of size
n + 1
Conclusion
The Sieve of Eratosthenes is an optimal algorithm to find all primes ≤ n.
Its time efficiency and simplicity make it a classic technique in number theory and competitive programming.