A surprising number of algorithm problems are number theory or counting in disguise. This lesson collects the math that shows up again and again: primes and the Sieve of Eratosthenes, GCD and LCM with Euclid's algorithm, modular arithmetic (the reason so many answers are "modulo 10⁹ + 7"), fast exponentiation, modular inverses and combinations. Each tool is short to code and turns a hopeless brute force into a logarithmic or near-linear algorithm.
Think of it like
Panning for gold
Pour every number from 2 to n into a pan. The first nugget, 2, is prime, so shake out all of its multiples. The next nugget left, 3, is prime too, so shake out its multiples. Keep going: whatever survives the shaking can never be split into smaller factors. That is the Sieve of Eratosthenes, and the visualization above runs exactly this process.
Primes and trial division
A prime is an integer greater than 1 whose only positive divisors are 1 and itself. The fundamental theorem of arithmetic says every integer greater than 1 factors into primes in exactly one way (ignoring order), for example 360 = 2³ × 3² × 5. Primes are the atoms of multiplication.
To test whether n is prime you only need to try divisors up to √n. If n = a × b with a ≤ b, then a × a ≤ a × b = n, so a ≤ √n. A composite number always has a divisor no larger than its square root.
def is_prime(n: int) -> bool:
if n < 2:
return False
if n % 2 == 0:
return n == 2
i = 3
while i * i <= n: # compare squares: no floating-point sqrt
if n % i == 0:
return False
i += 2 # even divisors were ruled out above
return TrueThe same loop factorizes n: whenever d divides n, divide it out as many times as possible and record the exponent. If anything greater than 1 is left after the loop, it is a single prime factor larger than √n. The total cost is still O(√n).
The Sieve of Eratosthenes
Trial division tests one number. When you need every prime up to n, running trial division n times costs O(n√n). The sieve does it in nearly linear time by crossing out multiples instead of testing divisors.
- 1
Start with every candidate
Mark every number from 2 to n as possibly prime.
- 2
Take the next survivor
The smallest number p still marked is prime: no smaller prime divides it.
- 3
Cross out its multiples
Mark p², p² + p, p² + 2p, … up to n as composite.
- 4
Stop at √n
Once p² > n there is nothing left to cross out. Every number still marked is prime.
| Prime p | Starts at p² | Newly crossed out (n = 30) |
|---|---|---|
| 2 | 4 | 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30 |
| 3 | 9 | 9, 15, 21, 27 (12, 18, 24, 30 were already crossed) |
| 5 | 25 | 25 (30 was already crossed) |
| 7 | 49 > 30 | Stop. Survivors: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29 |
Primes below 10⁶
78,498
π(10⁶)
Primes below 10⁷
664,579
π(10⁷)
Sieve to 10⁷
~10 MB
One byte per number, or ~1.25 MB as bits
ln ln 10⁹
≈ 3.03
Why the log log factor is nearly constant
- Smallest-prime-factor sieve: store
spf[i], the smallest prime dividing i, instead of a boolean. Then any number up to n factorizes in O(log n) by repeatedly dividing byspf. - Linear sieve: a variant that crosses out each composite exactly once, giving O(n) and the
spfarray for free. - Segmented sieve: sieve a window
[L, R]using the primes up to √R, for ranges far beyond what fits in memory.
GCD and Euclid's algorithm
The greatest common divisor gcd(a, b) is the largest integer dividing both. Euclid noticed that any common divisor of a and b also divides a − b, and therefore a mod b. So the problem shrinks without changing its answer.
| Step | a | b | a mod b |
|---|---|---|---|
| 1 | 252 | 105 | 42 (252 = 2 × 105 + 42) |
| 2 | 105 | 42 | 21 (105 = 2 × 42 + 21) |
| 3 | 42 | 21 | 0 (42 = 2 × 21) |
| 4 | 21 | 0 | Done: gcd = 21 |
Euclid's algorithm runs in O(log min(a, b)) steps: every two steps the larger argument at least halves. The worst case is two consecutive Fibonacci numbers (Lamé's theorem), which is why the bound is logarithmic with base φ.
LCM
Extended Euclid
Bézout's identity says there are integers x and y with a·x + b·y = gcd(a, b). The extended algorithm finds them by carrying coefficients back up the recursion: if b·x₁ + (a mod b)·y₁ = g, then x = y₁ and y = x₁ − ⌊a/b⌋·y₁.
Modular arithmetic
a mod m is the remainder after dividing by m. It is clock arithmetic: 9 o'clock plus 5 hours is 2 o'clock because (9 + 5) mod 12 = 2. Two numbers are congruent modulo m, written a ≡ b (mod m), when they leave the same remainder.
Counting problems often have astronomically large answers (100! has 158 digits), so they ask for the answer modulo a large prime, almost always 10⁹ + 7 or 998,244,353. Reducing after every addition and multiplication keeps every intermediate value below m, and the properties above guarantee the final remainder is identical to reducing the true answer once at the end.
- It is prime, so every non-zero residue has a multiplicative inverse, and division works via Fermat's little theorem.
- It fits in a signed 32-bit int, and so does the sum of two residues (about 2.0 × 10⁹ < 2³¹ − 1).
- The product of two residues fits in a signed 64-bit int: (10⁹ + 7)² ≈ 1.0 × 10¹⁸ < 9.22 × 10¹⁸.
Fast exponentiation
Computing aⁿ mod m with n multiplications is far too slow when n is 10¹⁸. Binary exponentiation reads n in binary: square the base at every step and multiply it into the result when the current bit is 1. That is O(log n) multiplications, the iterative form of the fast power in Recursion.
| n (binary) | Low bit | result | base after squaring |
|---|---|---|---|
13 (1101) | 1 | 1 × 3 = 3 | 3² mod 7 = 2 |
6 (110) | 0 | 3 (unchanged) | 2² mod 7 = 4 |
3 (11) | 1 | 3 × 4 mod 7 = 5 | 4² mod 7 = 2 |
1 (1) | 1 | 5 × 2 mod 7 = 3 | 2² mod 7 = 4 |
| 0 | Done: 3¹³ mod 7 = 3 |
Modular inverse
The inverse of a modulo m is the number x with a · x ≡ 1 (mod m). It exists exactly when gcd(a, m) = 1. Multiplying by the inverse is how you "divide" under a modulus.
Fermat's little theorem
- Inverse is
pow(a, p − 2, p) - Requires a prime modulus
- O(log p) with fast exponentiation
- One line once you have
mod_pow
Extended Euclid
- Solve
a·x + m·y = 1; then x is the inverse - Works for any modulus with gcd(a, m) = 1
- O(log m)
- Python 3.8+ has it built in:
pow(a, -1, m)
Combinatorics
- Product rule
- Independent choices multiply: 3 shirts and 4 pants make 12 outfits.
- Permutations
- Ordered arrangements of r out of n items: P(n, r) = n! / (n − r)!.
- Combinations
- Unordered selections of r out of n: C(n, r) = n! / (r! (n − r)!), read "n choose r".
- Stars and bars
- Ways to split n identical items into k groups (empty groups allowed): C(n + k − 1, k − 1).
- Catalan numbers
- C(2n, n) / (n + 1): balanced parentheses strings, binary tree shapes, monotonic lattice paths below the diagonal.
Pascal's triangle
| n | C(n, 0) … C(n, n) |
|---|---|
| 0 | 1 |
| 1 | 1 1 |
| 2 | 1 2 1 |
| 3 | 1 3 3 1 |
| 4 | 1 4 6 4 1 |
| 5 | 1 5 10 10 5 1 |
pascal function below. Add a modulus such as mod 6 to see a non-prime modulus work.Factorials with inverse factorials
For many queries with n up to 10⁶ or more, precompute fact[i] = i! mod p and inv_fact[i] = (i!)⁻¹ mod p. Compute inv_fact[n] once with Fermat, then walk down using inv_fact[i − 1] = inv_fact[i] × i. Every C(n, r) is then three table lookups and two multiplications.
| Method | Precompute | Per query | Use when |
|---|---|---|---|
| Pascal's triangle | O(n²) | O(1) | n up to a few thousand, or the modulus is not prime |
| Factorials + inverses | O(n + log p) | O(1) | n up to ~10⁷ with a prime modulus p > n |
| Multiplicative formula | None | O(r) | A single exact value with big integers |
Integer overflow
int32 max
2,147,483,647
About 2.1 × 10⁹
int64 max
≈ 9.22 × 10¹⁸
2⁶³ − 1
First factorial over int32
13!
6,227,020,800
First factorial over int64
21!
20! ≈ 2.43 × 10¹⁸ still fits
- Widen before multiplying. In Java and C++,
a * bwith twoints overflows before it is assigned to along. Write(long) a * bor1LL * a * b. - Reduce before multiplying. Keep residues below m so their product stays below m².
- Mind JavaScript numbers.
Numberis exact only up to 2⁵³ − 1 ≈ 9 × 10¹⁵, so the product of two residues near 10⁹ loses precision. UseBigIntfor modular multiplication. - Python never overflows, but huge integers get slow, so still reduce modulo m as you go.
- Midpoints:
lo + (hi - lo) / 2avoids overflowinglo + hiin Binary Search.
Complexity
| Algorithm | Time | Space | Notes |
|---|---|---|---|
| Primality by trial division | O(√n) | O(1) | Test divisors up to √n |
| Factorization by trial division | O(√n) | O(log n) | At most log₂ n prime factors |
| Sieve of Eratosthenes | O(n log log n) | O(n) | All primes up to n |
| Euclid's GCD | O(log min(a, b)) | O(1) | Iterative form |
| Extended Euclid | O(log min(a, b)) | O(log min(a, b)) | Recursion depth |
| Fast exponentiation | O(log n) | O(1) | Iterative binary exponentiation |
| Modular inverse (Fermat) | O(log p) | O(1) | Prime modulus only |
| nCr table (Pascal) | O(n²) | O(n²) | Any modulus |
| nCr via factorials | O(n) | O(n) | Then O(1) per query; prime modulus |
Implementation
The Sieve of Eratosthenes for all primes up to n, trial division for a single number, and prime factorization.
def sieve(n: int) -> list[int]:
"""All primes <= n in O(n log log n)."""
if n < 2:
return []
is_prime = [True] * (n + 1)
is_prime[0] = is_prime[1] = False
p = 2
while p * p <= n:
if is_prime[p]:
for multiple in range(p * p, n + 1, p): # start at p^2
is_prime[multiple] = False
p += 1
return [i for i, prime in enumerate(is_prime) if prime]
def is_prime(n: int) -> bool:
"""Trial division up to sqrt(n)."""
if n < 2:
return False
if n % 2 == 0:
return n == 2
i = 3
while i * i <= n:
if n % i == 0:
return False
i += 2
return True
def factorize(n: int) -> dict[int, int]:
"""Prime factorization as {prime: exponent} in O(sqrt(n))."""
factors: dict[int, int] = {}
d = 2
while d * d <= n:
while n % d == 0:
factors[d] = factors.get(d, 0) + 1
n //= d
d += 1
if n > 1: # leftover prime factor larger than sqrt
factors[n] = factors.get(n, 0) + 1
return factors
print(sieve(30)) # [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
print(is_prime(97)) # True
print(factorize(360)) # {2: 3, 3: 2, 5: 1}Key takeaways
- Test primality by trial division up to √n; find all primes up to n with the Sieve of Eratosthenes in O(n log log n), crossing out from p².
- Euclid's algorithm
gcd(a, b) = gcd(b, a mod b)runs in O(log min(a, b)); compute LCM asa / gcd × b. - Reduce modulo m after every addition and multiplication; normalize negatives with
((a % m) + m) % m. - Binary exponentiation computes aⁿ mod m in O(log n); with a prime p, the inverse of a is a^(p−2).
- For many nCr queries, precompute factorials and inverse factorials; use Pascal's triangle for small n or a non-prime modulus.
- Widen before multiplying and remember JavaScript numbers are exact only to 2⁵³.
Common pitfalls
- Starting the sieve's inner loop at 2p instead of p² (correct but slower) or looping p all the way to n instead of √n.
- Writing
(a / b) % munder a modulus instead of multiplying by the modular inverse of b. - Forgetting that
%can return negative values in C++, Java and JavaScript after a subtraction. - Computing
a * b % min 32-bit types, or with JavaScript numbers when a and b are near 10⁹. - Using Fermat's inverse with a non-prime modulus or when a is a multiple of p, where no inverse exists.
Interview tips
- When the statement says "modulo 10⁹ + 7", say up front that you will reduce at every step and use 64-bit products.
- Derive the √n bound for trial division out loud; it is a quick, convincing correctness argument.
- Know Euclid's algorithm cold; GCD shows up inside string problems, fraction simplification and array problems.
Real-world applications
- Cryptography: RSA relies on modular exponentiation, modular inverses and large primes.
- Hashing: polynomial rolling hashes in String Matching (KMP, Rabin-Karp, Z) are computed modulo a large prime.
- Counting problems and probability, where answers are reported modulo a prime.
- Simplifying fractions, scheduling with periodic events (LCM), and checksum algorithms.
Practice problems
Test yourself
What is the time complexity of the Sieve of Eratosthenes for all primes up to n?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.