Number Theory & Math for Programmers
GCD, primes and the sieve, modular arithmetic, fast exponentiation, modular inverse, combinatorics and overflow.
A small amount of number theory goes a long way: it underpins hashing, cryptography (RSA), random number generators, checksums, and a whole class of "answer modulo 10⁹ + 7" problems.
GCD and LCM — Euclid's algorithm
The greatest common divisor satisfies gcd(a, b) = gcd(b, a mod b), and gcd(a, 0) = a. It runs in O(log min(a, b)) — one of the oldest algorithms still in daily use (~300 BC).
(Divide before multiplying to avoid overflow.)
long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); }
long lcm(long a, long b) { return a / gcd(a, b) * b; }
// Extended Euclid: finds x, y with a·x + b·y = gcd(a, b)
long[] extGcd(long a, long b) {
if (b == 0) return new long[]{a, 1, 0};
long[] r = extGcd(b, a % b);
return new long[]{r[0], r[2], r[1] - (a / b) * r[2]};
}from math import gcd, lcm # built in (lcm: 3.9+)
def gcd_(a, b):
while b:
a, b = b, a % b
return a
def ext_gcd(a, b):
"""Returns (g, x, y) with a*x + b*y == g == gcd(a, b)."""
if b == 0:
return a, 1, 0
g, x, y = ext_gcd(b, a % b)
return g, y, x - (a // b) * yconst gcd = (a: number, b: number): number => (b === 0 ? a : gcd(b, a % b));
const lcm = (a: number, b: number) => (a / gcd(a, b)) * b;Primes
Trial division checks divisors up to √n: O(√n) — if n = a·b with a ≤ b, then a ≤ √n.
The Sieve of Eratosthenes finds all primes up to n in O(n log log n): for each prime p, cross out its multiples starting at p².
boolean[] sieve(int n) { // isComposite[i]
boolean[] composite = new boolean[n + 1];
for (int p = 2; (long) p * p <= n; p++)
if (!composite[p])
for (int m = p * p; m <= n; m += p) composite[m] = true;
return composite; // primes: i ≥ 2 with !composite[i]
}
boolean isPrime(long n) {
if (n < 2) return false;
for (long d = 2; d * d <= n; d++) if (n % d == 0) return false;
return true;
}def sieve(n):
is_prime = [True] * (n + 1)
is_prime[0:2] = [False, False]
for p in range(2, int(n ** 0.5) + 1):
if is_prime[p]:
is_prime[p * p::p] = [False] * len(range(p * p, n + 1, p))
return [i for i, v in enumerate(is_prime) if v]
def prime_factors(n):
f, d = [], 2
while d * d <= n:
while n % d == 0:
f.append(d); n //= d
d += 1
if n > 1:
f.append(n)
return ffunction sieve(n: number): number[] {
const composite = new Uint8Array(n + 1);
const primes: number[] = [];
for (let i = 2; i <= n; i++) {
if (composite[i]) continue;
primes.push(i);
for (let m = i * i; m <= n; m += i) composite[m] = 1;
}
return primes;
}For huge numbers (cryptography), primality is tested probabilistically with Miller-Rabin.
Modular arithmetic
Problems often say "return the answer modulo 10⁹ + 7" because the true answer overflows. Rules:
Subtraction: add m before taking the modulus, ((a - b) % m + m) % m, because % can return negatives in Java, JS and C. Division is not directly allowed — multiply by the modular inverse instead.
Fast exponentiation
Compute aᵇ mod m in O(log b) by squaring: aᵇ = (a^(b/2))² for even b.
long modPow(long base, long exp, long mod) {
long result = 1;
base %= mod;
while (exp > 0) {
if ((exp & 1) == 1) result = result * base % mod; // use this bit
base = base * base % mod; // square
exp >>= 1;
}
return result;
}
// Modular inverse when mod is prime (Fermat's little theorem): a^(p-2) mod p
long modInverse(long a, long p) { return modPow(a, p - 2, p); }pow(3, 200, 10**9 + 7) # built-in fast modular exponentiation
pow(5, -1, 10**9 + 7) # modular inverse (Python 3.8+)
def mod_pow(base, exp, mod):
result, base = 1, base % mod
while exp:
if exp & 1:
result = result * base % mod
base = base * base % mod
exp >>= 1
return resultfunction modPow(base: bigint, exp: bigint, mod: bigint): bigint {
let result = 1n;
base %= mod;
while (exp > 0n) {
if (exp & 1n) result = (result * base) % mod;
base = (base * base) % mod;
exp >>= 1n;
}
return result;
}
// Use BigInt: products of two numbers near 1e9 exceed 2^53 (Number's exact range).Combinatorics
| Quantity | Formula | Meaning |
|---|---|---|
| Permutations | n! | Orderings of n items |
| k-permutations | n! / (n − k)! | Ordered picks of k |
| Combinations C(n, k) | n! / (k! (n − k)!) | Unordered picks of k |
| Pascal's rule | C(n, k) = C(n−1, k−1) + C(n−1, k) | DP table |
| Catalan numbers | C(2n, n) / (n + 1) | Valid parentheses, BST shapes, triangulations |
For C(n, k) mod p with large n: precompute factorials and inverse factorials mod p in O(n), then each query is O(1). See Combinatorics for the theory.
Overflow and precision
- 32-bit int max is ~2.1 × 10⁹. The product of two ints can overflow — cast to long first:
(long) a * b. - JavaScript numbers are doubles: integers are exact only up to 2⁵³ − 1. Use
BigIntbeyond that. - Never compare floats with
==; use an epsilon, or avoid floats entirely (comparea·dvsb·cinstead ofa/bvsc/d). Math.abs(Integer.MIN_VALUE)is still negative in Java.
- Euclid's gcd is O(log n); lcm = a / gcd · b.
- Sieve of Eratosthenes: all primes ≤ n in O(n log log n); trial division to √n for one number.
- Reduce mod m after every + and ×; fix negatives after −; divide via modular inverse.
- Fast exponentiation is O(log b) — also the core of RSA.
- Watch overflow: long, BigInt, and exact integer comparisons.
QCount primes less than n.medium
Sieve of Eratosthenes up to n − 1 and count the survivors. Start crossing at p² and stop when p² ≥ n. O(n log log n) time, O(n) memory (a bitset reduces memory 8×).
QWhy is 10⁹ + 7 such a common modulus?easy
It's prime (so every non-zero value has a modular inverse), close to 2³⁰ so sums of two residues fit in a 32-bit int, and products of two residues fit in a 64-bit long.