Learn / Maths for DSA

Sieve

The sieve of Eratosthenes finds every prime up to n by crossing out multiples. Each prime p crosses out p², p² + p, …, because smaller multiples were already crossed by smaller primes. It runs in O(n log log n).

How to recognise it

  • All primes up to n, or counting them.
  • Many primality questions about numbers up to about 10⁷.
  • Smallest prime factors for fast factorisation.

Crossing out

composite = [false] × (n + 1)
for i in 2..n:
    if not composite[i]: i is prime
        for j from i × i to n step i: composite[j] = true

Watch for overflow in i × i: use a 64-bit value.

Common mistakes

  • Counting primes up to n when the problem asks for primes below n.
  • Treating 0 and 1 as prime.

Problems

0 of 2 solved

Check yourself

Why start crossing at p × p?

How many primes are below 10?

What is the time complexity?