Python Program for Sieve of Eratosthenes

The Sieve of Eratosthenes is an ancient algorithm for finding all prime numbers up to a given limit. It works by iteratively marking the multiples of each prime as composite, leaving only the prime numbers unmarked.

Problem statement − We are given a number n, we need to print all primes smaller than or equal to n. Constraint: n is a small number.

Algorithm Overview

The algorithm follows these steps:

  • Create a boolean array of size n+1, initially all True
  • Mark 0 and 1 as False (not prime)
  • For each number p from 2 to ?n, if p is still marked True, mark all multiples of p as False
  • The remaining True positions represent prime numbers

Implementation

def SieveOfEratosthenes(n):
    # array of type boolean with True values in it
    prime = [True for i in range(n + 1)]
    p = 2
    while (p * p <= n):
        # If it remain unchanged it is prime
        if (prime[p] == True):
            # updating all the multiples
            for i in range(p * 2, n + 1, p):
                prime[i] = False
        p += 1
    prime[0] = False
    prime[1] = False
    # Print
    for p in range(n + 1):
        if prime[p]:
            print(p, end=" ")

# main
if __name__ == '__main__':
    n = 33
    print("The prime numbers smaller than or equal to", n, "is")
    SieveOfEratosthenes(n)
The prime numbers smaller than or equal to 33 is
2 3 5 7 11 13 17 19 23 29 31

How It Works

Let's trace through the algorithm with a smaller example (n=10):

def detailed_sieve(n):
    prime = [True] * (n + 1)
    prime[0] = prime[1] = False  # 0 and 1 are not prime
    
    print(f"Initial array: {prime}")
    
    p = 2
    while p * p <= n:
        if prime[p]:
            print(f"Marking multiples of {p}")
            # Mark multiples of p as False
            for i in range(p * p, n + 1, p):
                prime[i] = False
            print(f"Array after marking multiples of {p}: {prime}")
        p += 1
    
    # Print prime numbers
    primes = [i for i in range(n + 1) if prime[i]]
    print(f"Prime numbers up to {n}: {primes}")

detailed_sieve(10)
Initial array: [False, False, True, True, True, True, True, True, True, True, True]
Marking multiples of 2
Array after marking multiples of 2: [False, False, True, True, False, True, False, True, False, True, False]
Marking multiples of 3
Array after marking multiples of 3: [False, False, True, True, False, True, False, True, False, False, False]
Prime numbers up to 10: [2, 3, 5, 7]

Time Complexity

The time complexity of the Sieve of Eratosthenes is O(n log log n), making it very efficient for finding all primes up to a moderate limit. The space complexity is O(n).

Sieve of Eratosthenes Visualization (n=20) 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 Prime Composite Steps: 1. Mark 0,1 as composite 2. Keep 2, mark 4,6,8,10,12,14,16,18,20 3. Keep 3, mark 9,15 4. Keep 5 (no new multiples ?20) 5. Result: 2,3,5,7,11,13,17,19

Conclusion

The Sieve of Eratosthenes is an efficient algorithm for finding all prime numbers up to a given limit. Its systematic approach of eliminating multiples makes it much faster than checking each number individually for primality.

Updated on: 2026-03-25T06:52:35+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements