Algorithm LogbookAlgorithm Logbook

The Sieve Of Eratosthenes

Basic Math

๐Ÿ“‹ Problem Statement

Given an integer NN, return a list of all prime numbers from 2 to NN (inclusive) using the Sieve of Eratosthenes algorithm. For example, N=30N = 30 โ†’ [2, 3, 5, 7, 11, 13, 17, 19, 23, 29].

๐Ÿ’ก Intuition

Instead of checking each number individually (which takes O(N)O(\sqrt{N}) per number), the Sieve marks all multiples of each prime as composite in bulk. Start from the smallest prime (2), mark all its multiples as not prime, then move to the next unmarked number, and repeat. The outer loop only runs up to N\sqrt{N} because any composite number's smallest prime factor must be โ‰คN\leq \sqrt{N}.

๐Ÿ”ง Approach

  1. Create a boolean array is_prime of size N+1N+1, initialized to True.
  2. Set is_prime[0] = is_prime[1] = False.
  3. For each ii from 2 to โŒŠNโŒ‹\lfloor \sqrt{N} \rfloor: if is_prime[i] is True, mark all multiples starting at i2i^2 as False.
  4. Collect all indices where is_prime[i] is still True.

โšก Complexity Analysis

Time

O(NlogโกlogโกN)O(N \log \log N) โ€” from the harmonic series over primes

Space

O(N)O(N) โ€” for the boolean sieve array

โš ๏ธ Common Mistakes

  • Starting the inner loop from 2i2i instead of i2i^2 โ€” the smaller multiples were already marked by earlier primes
  • Not marking 0 and 1 as non-prime before collecting results
  • Using a list of integers instead of a boolean array โ€” wastes memory

๐ŸŽฏ Final Thoughts

The Sieve of Eratosthenes is the gold standard for generating all primes up to NN. Understanding why the inner loop starts at i2i^2 (not 2i2i) and why the outer loop only goes to N\sqrt{N} is key to grasping its efficiency.