Bird
Raised Fist0
DSA Javaprogramming~15 mins

Sieve of Eratosthenes Find All Primes in DSA Java - Deep Dive

Choose your learning style10 modes available
Overview - Sieve of Eratosthenes Find All Primes
What is it?
The Sieve of Eratosthenes is a simple and efficient way to find all prime numbers up to a given number. It works by marking the multiples of each prime number starting from 2, so only primes remain unmarked. This method helps quickly identify primes without checking each number individually. It is a classic algorithm used in many areas of computer science and mathematics.
Why it matters
Finding prime numbers is important in many fields like cryptography, computer security, and number theory. Without an efficient way like the sieve, checking primes would be slow and costly for large numbers. This algorithm makes it possible to handle large ranges quickly, enabling secure communications and faster computations in real life.
Where it fits
Before learning this, you should understand basic loops, arrays, and the concept of prime numbers. After mastering the sieve, you can explore more advanced prime-related algorithms, such as segmented sieve or prime factorization techniques.
Mental Model
Core Idea
Start with all numbers marked as potential primes, then repeatedly remove multiples of each found prime to leave only primes unmarked.
Think of it like...
Imagine a classroom where every student is initially standing. The teacher tells every 2nd student to sit down, then every 3rd student still standing to sit down, and so on. At the end, only students in prime-numbered seats remain standing.
Numbers: 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
Mark multiples of 2: 2 3 x 5 x 7 x x x 11 x 13 x x
Mark multiples of 3: 2 3 x 5 6 7 x x 10 11 12 13 14 15 16
Remaining primes: 2 3 5 7 11 13
Build-Up - 6 Steps
1
FoundationUnderstanding Prime Numbers
šŸ¤”
Concept: Learn what prime numbers are and why they matter.
A prime number is a number greater than 1 that has no divisors other than 1 and itself. For example, 2, 3, 5, and 7 are primes. Knowing primes helps in many math and computer problems.
Result
You can identify if a number is prime by checking divisibility.
Understanding what primes are is essential before learning how to find them efficiently.
2
FoundationBasic Method to Check Primes
šŸ¤”
Concept: Check if a number is prime by testing divisibility up to its square root.
To check if a number n is prime, test if any number from 2 to sqrt(n) divides it evenly. If none do, n is prime. This is slow for many numbers but works for one number.
Result
You can verify primality but it is inefficient for large ranges.
Knowing this method shows why a faster approach like the sieve is needed.
3
IntermediateMarking Multiples to Remove Non-Primes
šŸ¤”Before reading on: do you think marking multiples of primes up to n is faster than checking each number individually? Commit to yes or no.
Concept: Instead of checking each number, mark multiples of primes as not prime to skip them.
Start with a list of numbers from 2 to n, all marked as true (potential primes). For each number starting at 2, if it is still true, mark all its multiples as false (not prime). Continue until you reach sqrt(n).
Result
Only numbers still marked true are primes.
Marking multiples in bulk reduces repeated work and speeds up prime finding.
4
IntermediateImplementing the Sieve Algorithm
šŸ¤”Before reading on: do you think we need to mark multiples starting from the prime itself or from its square? Commit to your answer.
Concept: Start marking multiples from the square of the prime to avoid redundant work.
For each prime p starting from 2, mark multiples from p*p, p*p+p, p*p+2p, etc. This is because smaller multiples were already marked by smaller primes. Stop when p exceeds sqrt(n).
Result
The sieve efficiently marks all non-primes with minimal checks.
Starting from p squared avoids unnecessary repeated marking, optimizing performance.
5
AdvancedJava Code for Sieve of Eratosthenes
šŸ¤”Before reading on: do you think using a boolean array is better than an integer array for marking primes? Commit to yes or no.
Concept: Use a boolean array to track prime status for each number up to n.
public class Sieve { public static void sieveOfEratosthenes(int n) { boolean[] prime = new boolean[n + 1]; for (int i = 2; i <= n; i++) { prime[i] = true; } for (int p = 2; p * p <= n; p++) { if (prime[p]) { for (int i = p * p; i <= n; i += p) { prime[i] = false; } } } System.out.print("Primes up to " + n + ": "); for (int i = 2; i <= n; i++) { if (prime[i]) { System.out.print(i + " "); } } System.out.println(); } public static void main(String[] args) { sieveOfEratosthenes(30); } }
Result
Primes up to 30: 2 3 5 7 11 13 17 19 23 29
Using a boolean array saves memory and clearly represents prime status.
6
ExpertOptimizing and Extending the Sieve
šŸ¤”Before reading on: do you think skipping even numbers after 2 improves the sieve's speed? Commit to yes or no.
Concept: Skip even numbers and use segmented sieve for very large ranges.
Since all even numbers except 2 are not prime, we can mark them false initially and only process odd numbers. For very large n, segmented sieve divides the range into smaller parts to save memory and improve cache usage.
Result
The sieve runs faster and uses less memory for large inputs.
Knowing these optimizations helps apply the sieve efficiently in real-world large-scale problems.
Under the Hood
The sieve uses an array representing numbers from 0 to n. Initially, all numbers except 0 and 1 are marked as potential primes (true). The algorithm iterates from 2 to sqrt(n). For each number still marked true, it marks all multiples as false. This process removes all composite numbers, leaving only primes marked true. The key is that multiples of smaller primes are removed early, so later primes only mark multiples starting from their square.
Why designed this way?
The sieve was designed to efficiently find primes by avoiding repeated divisibility checks for each number. Marking multiples in bulk reduces time complexity from checking each number individually. Starting from the square of each prime avoids redundant work because smaller multiples were already handled. This design balances simplicity and speed, making it practical for large ranges.
ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│ Numbers 2..n│
ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤
│ Initialize: │
│ prime[i]=T  │
ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤
│ For p=2 to  │
│ sqrt(n):    │
│   if prime[p]:
│     mark multiples
│     from p*p false
ā”œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”¤
│ Result:     │
│ prime[i]=T  │
│ means prime │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜
Myth Busters - 3 Common Misconceptions
Quick: Do you think the sieve marks multiples starting from 2*p or p*p? Commit to your answer.
Common Belief:The sieve marks multiples starting from 2 times the prime number.
Tap to reveal reality
Reality:The sieve starts marking multiples from the square of the prime number because smaller multiples were already marked by smaller primes.
Why it matters:Starting from 2*p causes redundant work and slows down the algorithm unnecessarily.
Quick: Do you think the sieve can find primes for negative numbers? Commit to yes or no.
Common Belief:The sieve can find primes for any integer, including negatives.
Tap to reveal reality
Reality:The sieve only works for positive integers greater than 1 because primes are defined in that range.
Why it matters:Applying the sieve to invalid ranges leads to incorrect results or errors.
Quick: Do you think the sieve is the fastest method for checking a single large number's primality? Commit to yes or no.
Common Belief:The sieve is the best way to check if a single large number is prime.
Tap to reveal reality
Reality:The sieve is efficient for finding all primes up to n, but for a single large number, probabilistic tests like Miller-Rabin are faster.
Why it matters:Using the sieve for single large numbers wastes time and memory.
Expert Zone
1
The sieve's time complexity is O(n log log n), which is much faster than naive methods but still not linear.
2
Memory usage can be a bottleneck for very large n; segmented sieve helps by processing smaller chunks.
3
Bitset implementations reduce memory further by storing prime flags as bits instead of booleans.
When NOT to use
Avoid using the sieve when checking primality of a single very large number; use probabilistic primality tests instead. Also, for extremely large ranges beyond memory limits, use segmented sieve or other memory-efficient algorithms.
Production Patterns
In production, the sieve is used to precompute primes for cryptographic key generation, random prime sampling, and mathematical libraries. It is often combined with segmented sieve for large ranges and bitset optimizations for memory efficiency.
Connections
Bit Manipulation
The sieve can be optimized using bit arrays to store prime flags efficiently.
Understanding bit manipulation helps reduce memory usage in prime sieves, enabling handling larger ranges.
Cryptography
Prime numbers found by the sieve are foundational for cryptographic algorithms like RSA.
Knowing how primes are generated helps understand the security basis of encryption.
Epidemiology Modeling
Both use iterative elimination processes to filter populations based on criteria.
Recognizing similar filtering patterns across fields reveals how algorithms model real-world spread or selection.
Common Pitfalls
#1Marking multiples starting from 2*p instead of p*p.
Wrong approach:for (int i = 2 * p; i <= n; i += p) { prime[i] = false; }
Correct approach:for (int i = p * p; i <= n; i += p) { prime[i] = false; }
Root cause:Misunderstanding that smaller multiples are already marked by previous primes.
#2Initializing the prime array with false instead of true for all numbers.
Wrong approach:boolean[] prime = new boolean[n + 1]; // all false by default // no initialization to true for 2..n
Correct approach:boolean[] prime = new boolean[n + 1]; for (int i = 2; i <= n; i++) { prime[i] = true; }
Root cause:Assuming default false means prime, but false means not prime in this context.
#3Including 0 and 1 as primes in the output.
Wrong approach:for (int i = 0; i <= n; i++) { if (prime[i]) System.out.print(i + " "); }
Correct approach:for (int i = 2; i <= n; i++) { if (prime[i]) System.out.print(i + " "); }
Root cause:Not recognizing that 0 and 1 are not prime numbers.
Key Takeaways
The Sieve of Eratosthenes efficiently finds all prime numbers up to a limit by marking multiples of primes as non-prime.
Starting to mark multiples from the square of each prime avoids redundant work and speeds up the algorithm.
Using a boolean array to track prime status is memory-efficient and clear in implementation.
The sieve is best for finding many primes at once, but not for checking a single large number's primality.
Optimizations like skipping even numbers and segmented sieves help handle very large ranges in practice.

Practice

(1/5)
1. What is the main purpose of the Sieve of Eratosthenes algorithm?
easy
A. To find all prime numbers up to a given limit
B. To sort an array of numbers
C. To find the greatest common divisor of two numbers
D. To reverse a string

Solution

  1. Step 1: Understand the algorithm's goal

    The Sieve of Eratosthenes is designed to identify prime numbers efficiently.
  2. Step 2: Recognize the output

    It marks multiples of primes as non-prime, leaving primes unmarked up to a limit.
  3. Final Answer:

    To find all prime numbers up to a given limit -> Option A
  4. Quick Check:

    Prime finding = To find all prime numbers up to a given limit [OK]
Hint: Sieve marks multiples to find primes fast [OK]
Common Mistakes:
  • Confusing with sorting algorithms
  • Thinking it finds divisors
  • Assuming it manipulates strings
2. Which of the following Java code snippets correctly initializes the boolean array for the sieve to find primes up to n?
easy
A. boolean[] prime = new boolean[n+1]; Arrays.fill(prime, false);
B. boolean[] prime = new boolean[n+1]; Arrays.fill(prime, true);
C. boolean[] prime = new boolean[n]; Arrays.fill(prime, false);
D. boolean[] prime = new boolean[n]; Arrays.fill(prime, true);

Solution

  1. Step 1: Check array size for indexing

    We need size n+1 to include number n as index.
  2. Step 2: Initialize all as true

    All numbers start as prime candidates, so fill with true.
  3. Final Answer:

    boolean[] prime = new boolean[n+1]; Arrays.fill(prime, true); -> Option B
  4. Quick Check:

    Array size n+1 and true fill = boolean[] prime = new boolean[n+1]; Arrays.fill(prime, true); [OK]
Hint: Use n+1 size and fill true for sieve array [OK]
Common Mistakes:
  • Using size n instead of n+1
  • Filling array with false initially
  • Confusing array size and indexing
3. What will be the output list of primes printed by the following Java code snippet for 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 + " ");
}
medium
A. 2 3 5 7
B. 2 3 4 5 7
C. 1 2 3 5 7
D. 2 3 5 7 9

Solution

  1. Step 1: Initialize primes and mark 0,1 false

    prime[0] and prime[1] are false; others true initially.
  2. Step 2: Mark multiples of primes false

    Multiples of 2 (4,6,8,10) and 3 (9) are marked false.
  3. Step 3: Print primes from 2 to 10

    Remaining true indices are 2,3,5,7.
  4. Final Answer:

    2 3 5 7 -> Option A
  5. Quick Check:

    Primes up to 10 = 2 3 5 7 [OK]
Hint: Mark multiples starting from p*p to optimize [OK]
Common Mistakes:
  • Including 1 as prime
  • Printing non-prime numbers like 4 or 9
  • Not starting inner loop from p*p
4. Identify the error in the following Java code snippet implementing the Sieve of Eratosthenes:
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;
    }
  }
}
medium
A. Arrays.fill should initialize with false, not true
B. The inner loop should start from p, not p*2
C. The outer loop should run only up to sqrt(n), not n
D. prime[0] and prime[1] should be true

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    The outer loop should run only up to sqrt(n), not n -> Option C
  4. Quick Check:

    Loop limit optimization = The outer loop should run only up to sqrt(n), not n [OK]
Hint: Outer loop limit is sqrt(n) for efficiency [OK]
Common Mistakes:
  • Running outer loop up to n wastes time
  • Starting inner loop incorrectly
  • Wrong initialization of prime array
5. You want to find all prime numbers up to n = 50 using the Sieve of Eratosthenes. After running the sieve, how many prime numbers will be found?
hard
A. 13
B. 16
C. 14
D. 15

Solution

  1. 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).
  2. Step 2: Count primes carefully

    Counting again: 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47 = 15 primes.
  3. Step 3: Verify options

    15 says 15, 16 says 16; correct count is 15.
  4. Final Answer:

    15 -> Option D
  5. Quick Check:

    Count primes ≤ 50 = 15 [OK]
Hint: Memorize primes or count after sieve [OK]
Common Mistakes:
  • Counting 1 as prime
  • Miscounting primes between 40 and 50
  • Assuming 16 primes instead of 15
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard