Sieve of Eratosthenes Find All Primes in DSA Java - Time & Space Complexity
We want to understand how the time needed to find all prime numbers grows as the input number gets bigger.
Specifically, how does the work change when we increase the limit up to which we find primes?
Analyze the time complexity of the following code snippet.
public void sieve(int n) {
boolean[] prime = new boolean[n + 1];
Arrays.fill(prime, true);
prime[0] = false;
prime[1] = false;
for (int i = 2; i * i <= n; i++) {
if (prime[i]) {
for (int j = i * i; j <= n; j += i) {
prime[j] = false;
}
}
}
}
This code marks all prime numbers up to n by crossing out multiples of each prime.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Nested loops where the outer loop runs over numbers up to √n, and the inner loop marks multiples of each prime.
- How many times: Outer loop runs about √n times; inner loop runs fewer times as i grows, crossing out multiples starting from i².
As n grows, the number of operations grows a bit faster than n but much less than n squared.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | ~20 operations |
| 100 | ~300 operations |
| 1000 | ~4,500 operations |
Pattern observation: The work grows roughly like n times the logarithm of the logarithm of n, which is slower than n log n but faster than linear.
Time Complexity: O(n log log n)
This means the time grows a bit faster than n but much slower than n squared, making it efficient for large n.
[X] Wrong: "The inner loop runs n times for each i, so the time is O(n²)."
[OK] Correct: The inner loop starts at i² and skips by i, so it runs fewer times as i grows, reducing total work significantly.
Understanding this algorithm's time complexity shows you can analyze nested loops with changing ranges, a common skill in coding interviews.
"What if we started the inner loop from 2*i instead of i*i? How would the time complexity change?"
Practice
Sieve of Eratosthenes algorithm?Solution
Step 1: Understand the algorithm's goal
The Sieve of Eratosthenes is designed to identify prime numbers efficiently.Step 2: Recognize the output
It marks multiples of primes as non-prime, leaving primes unmarked up to a limit.Final Answer:
To find all prime numbers up to a given limit -> Option AQuick Check:
Prime finding = To find all prime numbers up to a given limit [OK]
- Confusing with sorting algorithms
- Thinking it finds divisors
- Assuming it manipulates strings
n?Solution
Step 1: Check array size for indexing
We need size n+1 to include number n as index.Step 2: Initialize all as true
All numbers start as prime candidates, so fill with true.Final Answer:
boolean[] prime = new boolean[n+1]; Arrays.fill(prime, true); -> Option BQuick Check:
Array size n+1 and true fill = boolean[] prime = new boolean[n+1]; Arrays.fill(prime, true); [OK]
- Using size n instead of n+1
- Filling array with false initially
- Confusing array size and indexing
n = 10?
int n = 10;
boolean[] prime = new boolean[n+1];
Arrays.fill(prime, true);
prime[0] = false; prime[1] = false;
for (int p = 2; p * p <= n; p++) {
if (prime[p]) {
for (int i = p * p; i <= n; i += p) {
prime[i] = false;
}
}
}
for (int i = 2; i <= n; i++) {
if (prime[i]) System.out.print(i + " ");
}Solution
Step 1: Initialize primes and mark 0,1 false
prime[0] and prime[1] are false; others true initially.Step 2: Mark multiples of primes false
Multiples of 2 (4,6,8,10) and 3 (9) are marked false.Step 3: Print primes from 2 to 10
Remaining true indices are 2,3,5,7.Final Answer:
2 3 5 7 -> Option AQuick Check:
Primes up to 10 = 2 3 5 7 [OK]
- Including 1 as prime
- Printing non-prime numbers like 4 or 9
- Not starting inner loop from p*p
int n = 20;
boolean[] prime = new boolean[n+1];
Arrays.fill(prime, true);
prime[0] = false; prime[1] = false;
for (int p = 2; p <= n; p++) {
if (prime[p]) {
for (int i = p * 2; i <= n; i += p) {
prime[i] = false;
}
}
}Solution
Step 1: Check outer loop range
Outer loop runs from 2 to n, but it is enough to run up to sqrt(n) for efficiency.Step 2: Confirm inner loop start and initialization
Inner loop correctly starts at p*2; prime[0] and prime[1] are correctly false; array filled with true.Final Answer:
The outer loop should run only up to sqrt(n), not n -> Option CQuick Check:
Loop limit optimization = The outer loop should run only up to sqrt(n), not n [OK]
- Running outer loop up to n wastes time
- Starting inner loop incorrectly
- Wrong initialization of prime array
n = 50 using the Sieve of Eratosthenes. After running the sieve, how many prime numbers will be found?Solution
Step 1: List primes up to 50
Primes are 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47 (total 15).Step 2: Count primes carefully
Counting again: 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47 = 15 primes.Step 3: Verify options
15 says 15, 16 says 16; correct count is 15.Final Answer:
15 -> Option DQuick Check:
Count primes ≤ 50 = 15 [OK]
- Counting 1 as prime
- Miscounting primes between 40 and 50
- Assuming 16 primes instead of 15
Ready to prove it?
Pass the test and this pattern moves unknown
