About

Prime Numbers and Sieve of Eratosthenes

Prime Numbers: Brute Force and the Sieve of Eratosthenes

A prime number is an integer greater than 1 that has exactly two positive divisors: 1 and itself. The sequence of primes begins:

2,3,5,7,11,13,17,19,23,29,31,…2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, \dots

An integer greater than 1 that has more than two divisors is called a composite number. The number 1 is neither prime nor composite.


1. Brute-Force Prime Generation

Given an integer n≥2n \ge 2, we wish to list all primes between 22 and nn.

Definition-Based Brute Force

For every candidate integer xx from 22 to nn, test whether any divisor dd from 22 to x−1x - 1 divides xx evenly:

BruteForcePrimes(n):
    // Input: Integer n >= 2
    // Output: List of all prime numbers <= n
    primes = empty list
    for x = 2 to n do:
        isPrime = true
        for d = 2 to x - 1 do:
            if x mod d == 0 then:
                isPrime = false
                break
        if isPrime then:
            primes.append(x)
    return primes

Efficiency Analysis:

∑x=2n(x−2)=(n−2)(n−1)2=Θ(n2)\sum_{x=2}^n (x - 2) = \frac{(n-2)(n-1)}{2} = \Theta(n^2)

Square-Root Optimization

If x=a×bx = a \times b, at least one factor must satisfy a≤xa \le \sqrt{x}. If no divisor is found up to ⌊x⌋\lfloor \sqrt{x} \rfloor, xx must be prime:

OptimizedBruteForcePrimes(n):
    primes = empty list
    for x = 2 to n do:
        isPrime = true
        for d = 2 to floor(sqrt(x)) do:
            if x mod d == 0 then:
                isPrime = false
                break
        if isPrime then:
            primes.append(x)
    return primes

Efficiency Analysis:

∑x=2nx≈∫1nx1/2dx=23n3/2=Θ(nn)\sum_{x=2}^n \sqrt{x} \approx \int_1^n x^{1/2} dx = \frac{2}{3} n^{3/2} = \Theta(n\sqrt{n})

2. Sieve of Eratosthenes

The Sieve of Eratosthenes is an ancient and substantially more efficient algorithm that systematically eliminates multiples of primes rather than repeatedly testing division.

Algorithm Strategy

  1. Initialize a boolean array A[2..n] where every entry is initially true.
  2. For p=2,3,…,⌊n⌋p = 2, 3, \dots, \lfloor \sqrt{n} \rfloor:
    • If A[p] is still true, then pp is prime.
    • Cross out all multiples of pp starting at p2p^2:
    p2,p2+p,p2+2p,⋯≤np^2, p^2 + p, p^2 + 2p, \dots \le n (Note: Any multiple k×pk \times p with k<pk < p has already been crossed out by smaller prime factors!)
  3. Any number xx remaining true at the end is prime.
SieveOfEratosthenes(n):
    // Input: Integer n >= 2
    // Output: Array of all prime numbers <= n
    for p = 2 to n do A[p] = true

    for p = 2 to floor(sqrt(n)) do:
        if A[p] == true then:
            j = p * p
            while j <= n do:
                A[j] = false
                j = j + p

    primes = empty list
    for p = 2 to n do:
        if A[p] == true then:
            primes.append(p)
    return primes

Visual Trace: Sieve for n=25n = 25

⌊25⌋=5\lfloor \sqrt{25} \rfloor = 5. We only need outer loop passes for p=2,3,5p = 2, 3, 5:

NumberAfter p=2p=2 (eliminate ≥4\ge 4)After p=3p=3 (eliminate ≥9\ge 9)After p=5p=5 (eliminate ≥25\ge 25)Final Prime Status
2PrimePrimePrimePrime
3PrimePrimePrimePrime
4Eliminated (2×22 \times 2)--Composite
5PrimePrimePrimePrime
6Eliminated (2×32 \times 3)--Composite
7PrimePrimePrimePrime
9UndecidedEliminated (3×33 \times 3)-Composite
11PrimePrimePrimePrime
13PrimePrimePrimePrime
15Eliminated (2×…2 \times \dots)Eliminated (3×53 \times 5)-Composite
25UndecidedUndecidedEliminated (5×55 \times 5)Composite

Time & Space Complexity

∑p≤nnp≈n∑p≤n1p=Θ(nlog⁡log⁡n)\sum_{p \le \sqrt{n}} \frac{n}{p} \approx n \sum_{p \le n} \frac{1}{p} = \Theta(n \log \log n)

Because log⁡log⁡n\log \log n grows exceptionally slowly, this is virtually linear in practice.


Comparison Summary

AlgorithmMethodWorst-Case TimeAuxiliary SpaceKey Advantage
Brute Force (Definition)Test all d<xd < xΘ(n2)\Theta(n^2)Θ(1)\Theta(1)Simple to implement
Brute Force (Optimized)Test all d≤xd \le \sqrt{x}Θ(nn)\Theta(n\sqrt{n})Θ(1)\Theta(1)No memory overhead
Sieve of EratosthenesEliminate multiples from p2p^2Θ(nlog⁡log⁡n)\Theta(n \log \log n)Θ(n)\Theta(n)Vastly faster for ranges

Exercises

Exercise 1

In the Sieve of Eratosthenes, why does crossing out multiples of pp start at p2p^2 rather than 2p2p?

Show solution ↓
Solution

Any multiple of pp smaller than p2p^2 can be written as k×pk \times p where k<pk < p.

Since k<pk < p, kk must have a prime divisor q≤k<pq \le k < p. Consequently, this number k×pk \times p was already crossed out when the algorithm processed the smaller prime qq.

Starting at p2p^2 eliminates redundant crossing out operations.

Exercise 2

Calculate the number of operations required by the Sieve of Eratosthenes vs. the Brute-Force definition algorithm for n=10,000n = 10{,}000.

Show solution ↓
Solution
  • Brute Force: ≈n22=1082=50,000,000\approx \frac{n^2}{2} = \frac{10^8}{2} = 50{,}000{,}000 operations.
  • Sieve of Eratosthenes: ≈nlog⁡e(log⁡en)=10,000×ln⁡(ln⁡(10000))≈10,000×ln⁡(9.21)≈10,000×2.22≈22,200\approx n \log_e (\log_e n) = 10{,}000 \times \ln(\ln(10000)) \approx 10{,}000 \times \ln(9.21) \approx 10{,}000 \times 2.22 \approx 22{,}200 operations.

The Sieve is over 2,200 times faster for n=10,000n = 10{,}000.