Module 39
Math for Coding Interviews
GCD and LCM, primes with a sieve, modular arithmetic, fast exponentiation, modular inverses, nCr, and safe digit manipulation.
A handful of number-theory tools appear again and again: Euclid's GCD, the sieve of Eratosthenes, "return the answer modulo 10⁹ + 7", raising numbers to huge powers, dividing under a modulus, and counting arrangements with factorials.
This module explains each tool from first principles, shows the overflow traps in Java, and practises them on problems where the math replaces a loop or makes an impossible count possible.
Best after: Big-O and Complexity
Where this shows up in real systems
- System Design · System 12.1 — URL Shortener — Short codes are numbers written in base 62, the same base conversion as Excel column titles (base 26).
Part 1
Learn the ideas
- 39.1GCD, LCM and the Sievegcd(a, b) = gcd(b, a mod b) runs in O(log min(a, b)). lcm = a / gcd × b. The sieve marks multiples of each prime to find all primes below n in O(n log log n).14 min
- 39.2Modular Arithmetic, Fast Power and nCrReduce after every + and ×. Exponentiate by squaring in O(log e). Divide by multiplying with the modular inverse a^(p − 2) when p is prime.16 min
- 39.3Digits, Bases and OverflowExtract digits with % 10 and / 10, convert between bases by repeated division, and check for overflow before it happens.10 min
Part 2
Solve the problems
Work through them in order. Each one shows the pattern it teaches.
GCD applied to string lengths, after a commutativity check.
The sieve of Eratosthenes.
Bézout's identity: reachable amounts are multiples of gcd(x, y) up to x + y.
Base 26 with digits 1–26.
Count factors of 5 instead of computing n!.
Digit extraction with an overflow check before each step.
Fast modular exponentiation for counts with huge n.
An exponent given as a digit array: a^(10k + d) = (a^k)^10 × a^d.
Multinomial coefficients under a modulus with factorials and inverse factorials.