Number Theory & Math for Programmers

GCD, primes and the sieve, modular arithmetic, fast exponentiation, modular inverse, combinatorics and overflow.

Intermediate 3 min readLesson 18 of 18 Interview Q&A

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).

lcm⁡(a,b)=agcd⁡(a,b)⋅b\operatorname{lcm}(a, b) = \frac{a}{\gcd(a, b)} \cdot b

(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]};
}

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².

2345678910111213
Primes up to 13 survive; multiples of 2 and 3 are crossed out.
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;
}

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:

(a+b) mod m=((a mod m)+(b mod m)) mod m(a⋅b) mod m=((a mod m)(b mod m)) mod m(a + b) \bmod m = ((a \bmod m) + (b \bmod m)) \bmod m \qquad (a \cdot b) \bmod m = ((a \bmod m)(b \bmod m)) \bmod m

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); }

Combinatorics

QuantityFormulaMeaning
Permutationsn!Orderings of n items
k-permutationsn! / (n − k)!Ordered picks of k
Combinations C(n, k)n! / (k! (n − k)!)Unordered picks of k
Pascal's ruleC(n, k) = C(n−1, k−1) + C(n−1, k)DP table
Catalan numbersC(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 BigInt beyond that.
  • Never compare floats with ==; use an epsilon, or avoid floats entirely (compare a·d vs b·c instead of a/b vs c/d).
  • Math.abs(Integer.MIN_VALUE) is still negative in Java.
Key takeaways
  • 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.
Interview questions
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.