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:

Example 2:


Constraints


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:

  1. Assuming all numbers from 2 to n are prime.

  2. Iteratively marking the multiples of each prime as non-prime.


Approach

  1. Create a boolean array isPrime[] of size n + 1, initialized to true.

  2. Set isPrime[0] and isPrime[1] to false since 0 and 1 are not primes.

  3. Iterate i from 2 to √n:

    • If isPrime[i] == true, mark all multiples of i (starting from i*i) as false.
  4. After the loop, the indices in isPrime[] which remain true are 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

Step 1: i = 2

Step 2: i = 3

Resulting Primes: 2, 3, 5, 7


Time Complexity

Space Complexity


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.