Skip to lesson

Primes and the sieve

A prime number is an integer n ≥ 2 whose only positive divisors are 1 and n itself (0 and 1 are neither prime nor composite, and 2 is the only even prime). Knowing when to use O(√n) trial division for a single number versus an O(N log log N) sieve for a range is a staple of placement tests.

Trial Division Up to √n

The Sieve of Eratosthenes finds all primes up to n by crossing out the multiples of each prime, starting from 2, in O(n log log n) time.

A brute-force primality check tests every divisor from 2 to n - 1 in O(n) time. However, divisors always come in pairs (d, n / d): if d > √n, then its partner n / d must be < √n.

Example 1 · Brute force: test every divisor from 2 to n - 1 (O(n) time, O(1) space)

IsPrimeEveryDivisor.javaJava
public class IsPrimeEveryDivisor {    static long checks = 0;
    public static boolean isPrime(int n) {        if (n < 2) return false;        for (int d = 2; d < n; d++) {            checks++;            if (n % d == 0) {                return false;            }        }        return true;    }
    public static void main(String[] args) {        System.out.println("isPrime(97) = " + isPrime(97) + " after " + checks + " checks");        checks = 0;        System.out.println("isPrime(100) = " + isPrime(100) + " after " + checks + " checks");        checks = 0;        System.out.println("isPrime(1000003) = " + isPrime(1_000_003) + " after " + checks + " checks");    }}
Output
isPrime(97) = true after 95 checks
isPrime(100) = false after 1 checks
isPrime(1000003) = true after 1000001 checks

What this code does

  • The loop stops early for 100, because 2 divides it. A prime like 1 000 003 forces about a million checks.
  • Divisors come in pairs, so the check can stop much earlier, as the next example shows.

Example 2 · Better: trial division up to √n (O(√n) time, O(1) space)

TrialDivisionPrimeDemo.javaJava
public class TrialDivisionPrimeDemo {    public static boolean isPrime(int n) {        if (n < 2) return false;        if (n == 2) return true;        if (n % 2 == 0) return false;        for (int d = 3; d <= n / d; d += 2) {            if (n % d == 0) {                return false;            }        }        return true;    }
    public static void main(String[] args) {        System.out.println("isPrime(1) = " + isPrime(1));        System.out.println("isPrime(2) = " + isPrime(2));        System.out.println("isPrime(97) = " + isPrime(97));        System.out.println("isPrime(100) = " + isPrime(100));        System.out.println("isPrime(2147483647) = " + isPrime(Integer.MAX_VALUE));    }}
Output
isPrime(1) = false
isPrime(2) = true
isPrime(97) = true
isPrime(100) = false
isPrime(2147483647) = true

What this code does

  • Integer.MAX_VALUE (2³¹ - 1 = 2 147 483 647) is a Mersenne prime. Using d <= n / d stops safely at d = 46339 without overflowing d * d.
  • Handling 2 upfront lets the loop step by d += 2, cutting the number of division checks in half.
  • It is faster than testing every divisor because every divisor above √n has a partner below it.

Therefore, if a composite number n > 1 has any nontrivial divisor, its smallest prime divisor is at most ⌊√n⌋.

Testing divisors up to √n drops the time for a single primality check from O(n) to O(√n) — at most 46 340 iterations for any 32-bit int. In Java, write the loop bound as d <= n / d (or (long) d * d <= n) rather than d * d <= n: when n = Integer.MAX_VALUE (2³¹ - 1, which is prime), 46341 * 46341 overflows a 32-bit int to a negative number and causes an infinite loop!

  • Handle base cases first: if n < 2 return false; if n == 2 return true; if n % 2 == 0 return false.
  • Loop odd divisors for (int d = 3; d <= n / d; d += 2) and return false if n % d == 0.
  • Time complexity: O(√n) time and O(1) space per number.

Sieve of Eratosthenes

If you need to find all primes up to N (or answer Q primality queries for numbers up to N), calling O(√n) trial division for every number takes O(N√N) time.

  1. Hand trace of the sieve for N = 20: mark 0 and 1 as false, and 2..20 as true.
  2. p = 2 is prime (2² = 4 ≤ 20): cross out 4, 6, 8, 10, 12, 14, 16, 18, 20.
  3. p = 3 is prime (3² = 9 ≤ 20): cross out 9, 12, 15, 18 (starting at 3² = 9 since 6 = 2 × 3 was already crossed out by 2).
  4. p = 4 is already false, skip.
  5. p = 5 has 5² = 25 > 20, so the outer loop stops! Remaining true indices: 2, 3, 5, 7, 11, 13, 17, 19.

Sieve of Eratosthenes up to 16

Step 1 of 5

Array: 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16.
Start with every number from 2 to 16 as a possible prime. Nothing is crossed out yet.

Example 3 · Optimal for many numbers: Sieve of Eratosthenes (O(N log log N) time, O(N) space)

SieveOfEratosthenesDemo.javaJava
import java.util.ArrayList;import java.util.Arrays;import java.util.List;
public class SieveOfEratosthenesDemo {    public static boolean[] buildSieve(int n) {        boolean[] isPrime = new boolean[n + 1];        if (n >= 2) {            Arrays.fill(isPrime, 2, n + 1, true);        }        for (int p = 2; p <= n / p; p++) {            if (isPrime[p]) {                for (int multiple = p * p; multiple <= n; multiple += p) {                    isPrime[multiple] = false;                }            }        }        return isPrime;    }
    public static void main(String[] args) {        boolean[] sieve30 = buildSieve(30);        List<Integer> primesUpTo30 = new ArrayList<>();        for (int i = 2; i <= 30; i++) {            if (sieve30[i]) primesUpTo30.add(i);        }        System.out.println("Primes <= 30: " + primesUpTo30);
        boolean[] sieve100 = buildSieve(100);        int count100 = 0;        for (int i = 2; i <= 100; i++) {            if (sieve100[i]) count100++;        }        System.out.println("Prime count <= 100: " + count100);    }}
Output
Primes <= 30: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
Prime count <= 100: 25

What this code does

  • Once buildSieve(N) finishes in O(N log log N) time, any primality check sieve[x] for 0 ≤ x ≤ N is an O(1) array lookup.
  • The outer loop only runs while p <= n / p, and the inner loop starts at p * p.
  • It is faster than trial division for a whole range because each composite is crossed out by its smallest prime, with no division tests.

The Sieve of Eratosthenes flips the approach: instead of testing divisors of each number, it starts with a boolean array isPrime[0..N] initialized to true (except indices 0 and 1) and crosses out multiples of each prime.

When the outer loop reaches a prime p, the inner loop marks its composite multiples starting at p²: p², p² + p, p² + 2p, … ≤ N. Why start at p² instead of 2p? Because any smaller multiple k · p with 2 ≤ k < p has a prime factor ≤ k < p and was already crossed out during an earlier pass! By the harmonic sum over primes (Σ[p ≤ N] N/p ≈ N ln ln N), the entire sieve runs in O(N log log N) time and O(N) space.

Order of execution

Order the sieve steps

Put the steps of the sieve in the right order.

In the inner loop for (int m = p * p; m <= n; m += p), ensure p <= n / p in the outer loop so p * p never overflows int.

Prime Factorisation in O(√n)

By the Fundamental Theorem of Arithmetic, every integer n ≥ 2 factors uniquely into a product of primes. To extract all prime factors of n in ascending order, loop d from 2 while d ≤ n / d.

Example 4 · Prime Factorisation in O(√n) Time

PrimeFactorisationDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class PrimeFactorisationDemo {    public static List<Integer> primeFactors(int n) {        List<Integer> factors = new ArrayList<>();        while (n % 2 == 0) {            factors.add(2);            n /= 2;        }        for (int d = 3; d <= n / d; d += 2) {            while (n % d == 0) {                factors.add(d);                n /= d;            }        }        if (n > 1) {            factors.add(n);        }        return factors;    }
    public static void main(String[] args) {        System.out.println("Factors of 360: " + primeFactors(360));        System.out.println("Factors of 84:  " + primeFactors(84));        System.out.println("Factors of 97:  " + primeFactors(97));    }}
Output
Factors of 360: [2, 2, 2, 3, 3, 5]
Factors of 84:  [2, 2, 3, 7]
Factors of 97:  [97]

What this code does

  • For 84, dividing out 2 twice leaves 21, dividing out 3 leaves 7, and since 5 > 7 / 5, the loop exits and the final if (n > 1) appends the remaining prime 7.
  • For a prime input like 97, the loop runs up to d = 9 without dividing, and if (n > 1) appends 97.

Whenever d divides n, record d and divide n by d repeatedly (while (n % d == 0) { factors.add(d); n /= d; }).

Why is every recorded divisor d guaranteed to be prime? Because before d is reached, every smaller prime factor of n has already been completely divided out of n! And if n > 1 after the loop finishes, the remaining value of n is itself a prime factor (the unique prime factor of the original number that exceeded √n, if one existed).

  • Divide out 2 first in a while (n % 2 == 0) loop, then test odd d = 3, 5, 7, ... while d <= n / d.
  • Because n shrinks each time a factor is divided out, the loop condition d <= n / d tightens dynamically.
  • Do not forget the tail check if (n > 1) factors.add(n); — for example, on n = 14, dividing out 2 leaves n = 7, and since 3 > 7 / 3, the loop ends with the prime 7 still in n.

Next step

Check your understanding

10 quick questions