VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sieve-of-eratosthenes/

⇱ Sieve of Eratosthenes - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sieve of Eratosthenes

Last Updated : 23 Jul, 2025

Given a number n, find all prime numbers less than or equal to n.

Examples:

Input: n = 10
Output: [2, 3, 5, 7]
Explanation: The prime numbers up to 10 obtained by Sieve of Eratosthenes are [2, 3, 5, 7].

Input: n = 35
Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]
Explanation: The prime numbers up to 35 obtained by Sieve of Eratosthenes are [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31].

[Naive Approach] - Using Loop O(n*sqrt(n)) Time and O(1) Space

The Naive Approach for finding all prime numbers from 1 to n involves checking each number individually to determine whether it is prime.

Step By Step Implementations:

  • Loop through all numbers i from 2 to n.
  • For each i, check if it is divisible by any number from 2 to i - 1.
  • If it is divisible, then i is not prime.
  • If it is not divisible by any number in that range, then i is prime.

[Efficient Approach] - Sieve of Eratosthenes

The Sieve of Eratosthenes efficiently finds all primes up to n by repeatedly marking multiples of each prime as non-prime, starting from 2. This avoids redundant checks and quickly filters out all composite numbers.

Step By Step Implementations:

  • Initialize a Boolean array prime[0..n] and set all entries to true, except for 0 and 1 (which are not primes).
  • Start from 2, the smallest prime number.
  • For each number p from 2 up to √n:
    • If p is marked as prime(true):
    • Mark all multiples of p as not prime(false), starting from p * p (since smaller multiples have already been marked by smaller primes).
  • After the loop ends, all the remaining true entries in prime represent prime numbers.

Output
2 3 5 7 11 13 17 19 23 29 31 

Time Complexity: O(n*log(log(n))). For each prime number, we mark its multiples, which takes around n/p steps. The total time is proportional to n*(1/2 + 1/3 + 1/5 + ....).
This sum over primes grows slowly and is approximately O(n*log(log(n))) making the algorithm very efficient.
Auxiliary Space: O(n)

Related articles

Comment