M34 · Math

Primes with the Sieve of Eratosthenes

Trial division tests each number separately; the sieve shares the work by crossing out multiples of each prime once. This lesson explains the two optimisations that make it fast (start at p², stop at √n), derives O(n log log n), and covers memory, overflow and language notes for C#, Java, Python and C++.

~35 minIntermediateC# · Python · Java · C++
Curriculum: M34 Math · 2 of 2 lessons available

You will be able to

  • Run the Sieve of Eratosthenes by hand and explain why the numbers left unmarked are prime.
  • Justify starting each prime’s marking at p² and stopping the outer loop when p² > n.
  • Derive the O(n log log n) time bound and compare it with trial division.
  • Write the loop bounds without integer overflow and pick a memory-efficient flag array in each language.

Helpful before this lesson

  • M03 Big O — Count operations, describe growth, and tell worst-case, average and amortized costs apart.

Guidance only. Those modules are planned; the essentials are recapped here.

Visual walkthrough

The interactive visualizer needs JavaScript. The explanation and all four implementations below work without it.

Mental model

A number greater than 1 is prime if no smaller number other than 1 divides it. Testing one number k by trial division up to √k is fine; testing every number up to n that way repeats a lot of work.

The sieve turns the question around: instead of asking "does anything divide k?", every prime announces its multiples. Write down 2 … n. The smallest number not yet crossed out is prime; cross out all its multiples; repeat. Whatever survives has no smaller prime factor, so it is prime.

The algorithm

composite = array of n + 1 false values
for p = 2, 3, … while p * p <= n:
    if composite[p]: continue          # not prime: a smaller prime already did its work
    for m = p * p, p * p + p, … while m <= n:
        composite[m] = true
return every k in 2 … n with composite[k] == false

The lab lays 1 … n out in rows of ten. The current prime p has a pin, the number being crossed out is labelled with its factorisation k·p, crossed-out numbers fade, and primes light up.

Why start at p²?

Every multiple k · p with k < p has a prime factor smaller than p (a factor of k), so it was crossed out when that smaller prime was processed. The first multiple that may still be unmarked is p · p. For p = 7 and n = 50: 14, 21, 28, 35 and 42 are already gone; only 49 is new.

Why stop when p² > n?

A composite number c ≤ n can be written as c = a · b with 2 ≤ a ≤ b, so a² ≤ c ≤ n: it has a factor at most √n, and therefore a prime factor at most √n. Once p² > n, every composite up to n has been crossed out by some prime below p. For n = 50 only 2, 3, 5 and 7 do any marking (preset n = 50); 11² = 121 is too large.

Complexity

Prime p crosses out about n / p numbers. Summed over the primes up to √n:

n/2 + n/3 + n/5 + n/7 + … = n · Σ 1/p  ≈  n · ln ln n

The sum of reciprocals of primes up to x grows like ln ln x (Mertens' second theorem), which is why the sieve is O(n log log n) time, practically linear: ln ln 10⁹ ≈ 3. Memory is O(n) flags.

Some numbers are crossed out more than once, 12 by 2 and by 3, 30 by 2, 3 and 5. The lab's Repeat marks metric counts them. A linear sieve avoids repeats by crossing out each composite only by its smallest prime factor, reaching O(n), at the price of storing the prime list as it goes.

Method Time to list primes ≤ n Memory
Trial division of each k up to √k O(n √n) (less with only prime divisors) O(1) besides the output
Sieve of Eratosthenes O(n log log n) O(n) flags
Linear sieve O(n) O(n) flags + primes
Segmented sieve O(n log log n) O(√n) at a time

For a single primality test of a large number, use trial division up to √k or Miller–Rabin. For many queries up to a known bound, sieve once and look up.

Practical details

Overflow in the loop bounds. p * p <= n overflows a 32-bit int when p exceeds 46,340, even if n itself fits. The C#, Java and C++ listings write p <= n / p instead. The inner m += p can also overflow when n is within p of int.MaxValue; for such n use 64-bit loop variables.

Memory. A bool[] in C# and Java uses one byte per flag, and a Python list of booleans one pointer (8 bytes) per entry. For large n:

  • C#: BitArray, or a ulong[] with your own masks (the bit lesson's set and test);
  • Java: java.util.BitSet;
  • Python: bytearray(n + 1), which also allows slice assignment composite[p*p::p] = b"\x01" * len(range(p*p, n + 1, p)) to cross out a whole progression at C speed;
  • C++: std::vector<bool> already packs one flag per bit (the listing uses it), at the cost of proxy references instead of real bool&.

Only odd numbers need storing after 2, which halves memory again. Beyond memory limits, a segmented sieve processes [L, L + Δ) blocks using the primes up to √n.

Cache behaviour. Each prime walks the whole array with stride p, which misses the cache for large n; segmented sieves fix this too, because each block fits in cache.

Language notes

  • C#: new bool[n + 1] is zero-initialised (all false). checked arithmetic catches the bound overflow if you prefer an exception to a rewrite.
  • Java: boolean[] is also zero-initialised; BitSet.nextClearBit(k) walks to the next candidate.
  • Python: the listing's outer loop checks p * p > n explicitly (ints never overflow); math.isqrt(n) gives the exact integer square root for the bound, unlike int(n ** 0.5), which can be off by one for large n because of floating point.
  • C++: std::vector<bool>(n + 1) is false-initialised; index it with std::size_t, and avoid std::sqrt for the bound for the same floating-point reason.

The teaching implementation

The sieve shares a source file with Euclid's algorithm in each language. Each language reads one shared fixture (n = 0, 1, 2, 3, 4, perfect squares such as 25 and 49, a prime limit 97, 150) and compares the result with trial division for every n below 200 and for n = 5,000, where there are 669 primes. The unit tests of the trace also check that every crossed-out number is first marked by its smallest prime factor and that each prime starts at p².

Common mistakes

  • Starting at 2p instead of p²: correct, but does redundant work.
  • Looping p up to n instead of √n: correct, but the outer loop runs n times for nothing.
  • Forgetting that 0 and 1 are not prime when collecting the result.
  • Writing p * p <= n in 32-bit arithmetic for large n.
  • Using sqrt in floating point for the bound without checking the result.

Edge cases

  • n < 2: no primes; the outer loop never runs.
  • n = 2 or 3: the outer loop does not run either (2² > 3), and the collection step returns them.
  • n a perfect square (25, 49): p = √n still runs, because p² ≤ n, and crosses out n itself.

Worked practice

1. Which numbers does p = 5 cross out for n = 40, and which of them were already crossed out?

Answer

25, 30, 35 and 40. 30 (by 2 and 3) and 40 (by 2) were already crossed out; 25 and 35 are new.

2. For n = 1,000, which primes do any crossing out?

Answer

The primes up to √1000 ≈ 31.6: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31.

3. How would you find all primes in [10⁹, 10⁹ + 10⁶] without an array of size 10⁹?

Answer

Sieve the primes up to √(10⁹ + 10⁶) ≈ 31,639 first. Then allocate flags for the million numbers in the range only, and for each small prime p cross out its multiples from the first one ≥ max(p², 10⁹) inside the range. That is a segmented sieve.

Summary

  • Each prime crosses out its multiples; what survives is prime.
  • Start at p² (smaller multiples have smaller prime factors) and stop when p² > n (every composite has a prime factor ≤ √n).
  • O(n log log n) time, O(n) memory; pack flags as bits and write the bound as p <= n / p.

Full implementation

The sieve in four languages, each checked against one shared fixture (n = 0, 1, 2, perfect squares, 150) and against trial division for every n below 200 and for n = 5,000 (669 primes).

namespace Bekadan.Dsa.Examples.Mathematics;
 
/// <summary>
/// Euclid's GCD (with LCM) and the Sieve of Eratosthenes. Built-ins:
/// <see cref="System.Numerics.BigInteger.GreatestCommonDivisor"/>; .NET has no
/// LCM or sieve in the base library.
/// </summary>
public static class NumberTheory
{
    /// <summary>gcd(a, b) for a, b ≥ 0; gcd(a, 0) = a. O(log min(a, b)) iterations.</summary>
    public static long Gcd(long a, long b)
    {
        if (a < 0 || b < 0) throw new ArgumentOutOfRangeException(nameof(a), "Use non-negative numbers.");
        while (b != 0)
        {
            (a, b) = (b, a % b);  // gcd(a, b) = gcd(b, a mod b)
        }
        return a;
    }
 
    /// <summary>lcm(a, b) for a, b ≥ 0; 0 if either is 0. Throws if the result does not fit a long.</summary>
    public static long Lcm(long a, long b)
    {
        return a == 0 || b == 0 ? 0 : checked(a / Gcd(a, b) * b);  // divide first: a * b may overflow
    }
 
    /// <summary>All primes ≤ n. O(n log log n) time, O(n) memory.</summary>
    public static List<int> Sieve(int n)
    {
        var composite = new bool[Math.Max(n + 1, 0)];  // false: still a prime candidate
        for (int p = 2; p <= n / p; p++)  // p * p <= n, written so it cannot overflow
        {
            if (composite[p]) continue;  // a smaller prime factor already marked its multiples
            for (int m = p * p; m <= n; m += p)  // k·p for k < p was marked by a factor of k
                composite[m] = true;
        }
        var primes = new List<int>();
        for (int k = 2; k <= n; k++)
            if (!composite[k]) primes.Add(k);
        return primes;
    }
}

Tested on .NET 10 (SDK 10.0.403), C# 14 · examples/csharp/Bekadan.Dsa.Examples/Mathematics/NumberTheory.cs

"""Euclid's GCD (with LCM) and the Sieve of Eratosthenes.
 
Built-ins: math.gcd and math.lcm (3.9+). Python ints never overflow, so
a * b // gcd would also be exact, just slower for huge numbers.
"""
 
 
def gcd(a: int, b: int) -> int:
    """gcd(a, b) for a, b >= 0; gcd(a, 0) = a. O(log min(a, b)) iterations."""
    if a < 0 or b < 0:
        raise ValueError("use non-negative numbers")
    while b != 0:
        a, b = b, a % b  # gcd(a, b) = gcd(b, a mod b)
    return a
 
 
def lcm(a: int, b: int) -> int:
    """lcm(a, b) for a, b >= 0; 0 if either is 0."""
    return 0 if a == 0 or b == 0 else a // gcd(a, b) * b  # divide first: smaller intermediate
 
 
def sieve(n: int) -> list[int]:
    """All primes <= n. O(n log log n) time, O(n) memory."""
    composite = [False] * (n + 1) if n >= 0 else []  # False: still a prime candidate
    for p in range(2, n + 1):
        if p * p > n:
            break
        if composite[p]:
            continue  # a smaller prime factor already marked its multiples
        for m in range(p * p, n + 1, p):  # k*p for k < p was marked by a factor of k
            composite[m] = True
    return [k for k in range(2, n + 1) if not composite[k]]

Tested on CPython 3.14.0 · examples/python/dsa_examples/number_theory.py

package dev.bekadan.dsa.math;
 
import java.util.ArrayList;
import java.util.List;
 
/**
 * Euclid's GCD (with LCM) and the Sieve of Eratosthenes. Built-ins:
 * {@link java.math.BigInteger#gcd}; the JDK has no LCM or sieve.
 */
public final class NumberTheory {
    private NumberTheory() {
    }
 
    /** gcd(a, b) for a, b &gt;= 0; gcd(a, 0) = a. O(log min(a, b)) iterations. */
    public static long gcd(long a, long b) {
        if (a < 0 || b < 0) {
            throw new IllegalArgumentException("use non-negative numbers");
        }
        while (b != 0) {
            long r = a % b; // gcd(a, b) = gcd(b, a mod b)
            a = b;
            b = r;
        }
        return a;
    }
 
    /** lcm(a, b) for a, b &gt;= 0; 0 if either is 0. Throws ArithmeticException on overflow. */
    public static long lcm(long a, long b) {
        return a == 0 || b == 0 ? 0 : Math.multiplyExact(a / gcd(a, b), b); // divide first: a * b may overflow
    }
 
    /** All primes &lt;= n. O(n log log n) time, O(n) memory. */
    public static List<Integer> sieve(int n) {
        boolean[] composite = new boolean[Math.max(n + 1, 0)]; // false: still a prime candidate
        for (int p = 2; p <= n / p; p++) { // p * p <= n, written so it cannot overflow
            if (composite[p]) {
                continue; // a smaller prime factor already marked its multiples
            }
            for (int m = p * p; m <= n; m += p) { // k*p for k < p was marked by a factor of k
                composite[m] = true;
            }
        }
        List<Integer> primes = new ArrayList<>();
        for (int k = 2; k <= n; k++) {
            if (!composite[k]) {
                primes.add(k);
            }
        }
        return primes;
    }
}

Tested on Java 25 (Temurin 25.0.5); also compiles on Java 17 · examples/java/src/main/java/dev/bekadan/dsa/math/NumberTheory.java

#pragma once
 
#include <cstdint>
#include <stdexcept>
#include <vector>
 
namespace bekadan::dsa {
 
// Euclid's GCD (with LCM) and the Sieve of Eratosthenes.
// Built-ins: std::gcd and std::lcm in <numeric> (C++17); std::lcm does not
// report overflow (the result is undefined if it does not fit).
 
// gcd(a, b) for a, b >= 0; gcd(a, 0) = a. O(log min(a, b)) iterations.
inline std::int64_t gcd(std::int64_t a, std::int64_t b) {
    if (a < 0 || b < 0) throw std::invalid_argument("use non-negative numbers");
    while (b != 0) {
        const std::int64_t r = a % b;  // gcd(a, b) = gcd(b, a mod b)
        a = b;
        b = r;
    }
    return a;
}
 
// lcm(a, b) for a, b >= 0; 0 if either is 0. Throws instead of overflowing
// (signed overflow would be undefined behaviour).
inline std::int64_t lcm(std::int64_t a, std::int64_t b) {
    if (a == 0 || b == 0) return 0;
    std::int64_t result = 0;
    if (__builtin_mul_overflow(a / gcd(a, b), b, &result)) throw std::overflow_error("lcm does not fit in 64 bits");
    return result;  // divide first: a * b may overflow even when the lcm fits
}
 
// All primes <= n. O(n log log n) time, O(n) memory (std::vector<bool> packs bits).
inline std::vector<int> sieve(int n) {
    std::vector<bool> composite(n >= 0 ? static_cast<std::size_t>(n) + 1 : 0, false);  // false: still a candidate
    for (int p = 2; p <= n / p; ++p) {  // p * p <= n, written so it cannot overflow
        if (composite[static_cast<std::size_t>(p)]) continue;  // a smaller prime factor already marked its multiples
        for (int m = p * p; m <= n; m += p) composite[static_cast<std::size_t>(m)] = true;  // k*p for k < p is done
    }
    std::vector<int> primes;
    for (int k = 2; k <= n; ++k)
        if (!composite[static_cast<std::size_t>(k)]) primes.push_back(k);
    return primes;
}
 
}  // namespace bekadan::dsa

Tested on C++23, GCC 15.3 (libstdc++) · examples/cpp/include/bekadan/dsa/number_theory.hpp

References