Math and Number Theory — Master Recap and Interview Cheatsheet
Advertisement
Math and Number Theory Master Recap
Complete cheatsheet for number theory algorithms used across all 19 problems in this series.
Algorithm Selection Guide
| Problem Pattern | Algorithm | Complexity |
|---|---|---|
| All primes up to n | Sieve of Eratosthenes | O(n log log n) |
| Factorize one number | Trial division | O(sqrt n) |
| Factorize many numbers | SPF sieve + lookup | O(n log log n) + O(log n) |
| GCD of two numbers | Euclidean | O(log min) |
| Modular inverse (prime mod) | Fermat little theorem | O(log mod) |
| Modular inverse (any mod) | Extended GCD | O(log a) |
| a^n mod m | Binary exponentiation | O(log n) |
| nCr mod prime | Precomputed factorials | O(n) build, O(1) query |
| Fibonacci(10^18) | Matrix exponentiation | O(log n) |
| Count divisors | Factor then multiply exponents | O(sqrt n) |
| Sum of divisors | Factor then formula | O(sqrt n) |
| Euler totient(n) | Trial factorization | O(sqrt n) |
| All totients to n | Sieve variant | O(n log log n) |
| Nim game | XOR all piles | O(n) |
| System of modular equations | CRT | O(k log m) |
| Range queries | Sqrt decomposition | O(sqrt n) |
Template Library
MOD = 10**9 + 7
# Fast power
def pw(b, e, m=MOD):
return pow(b, e, m)
# Modular inverse (prime modulus only)
def inv(a, m=MOD):
return pow(a, m - 2, m)
# GCD and LCM
from math import gcd
def lcm(a, b):
return a // gcd(a, b) * b # divide FIRST to avoid overflow
# Factorial table for nCr
def build_fact(n, m=MOD):
f = [1] * (n + 1)
for i in range(1, n + 1):
f[i] = f[i-1] * i % m
fi = [1] * (n + 1)
fi[n] = inv(f[n])
for i in range(n - 1, -1, -1):
fi[i] = fi[i+1] * (i+1) % m
return lambda n, k: f[n] * fi[k] % m * fi[n-k] % m if 0 <= k <= n else 0
C = build_fact(10**6)
# Sieve
def sieve(n):
p = [True] * (n + 1)
p[0] = p[1] = False
for i in range(2, int(n**0.5) + 1):
if p[i]:
for j in range(i*i, n+1, i):
p[j] = False
return p
# SPF sieve (smallest prime factor for fast factorization)
def spf_sieve(n):
s = list(range(n + 1))
for i in range(2, int(n**0.5) + 1):
if s[i] == i:
for j in range(i*i, n+1, i):
if s[j] == j:
s[j] = i
return sComplexity Summary
| Algorithm | Time | Space |
|---|---|---|
| Sieve | O(n log log n) | O(n) |
| GCD | O(log n) | O(1) |
| Fast Pow | O(log n) | O(1) |
| nCr precomputed | O(n) build, O(1) query | O(n) |
| Prime factorize | O(sqrt n) | O(log n) |
| Extended GCD | O(log min(a,b)) | O(1) |
Top 25 Math/Number Theory LeetCode Problems
| LC | Problem | Key Technique |
|---|---|---|
| 50 | Pow(x,n) | Binary exponentiation |
| 69 | Sqrt(x) | Binary search |
| 149 | Max Points on a Line | GCD slope normalization |
| 172 | Factorial Trailing Zeros | Count factors of 5 |
| 204 | Count Primes | Sieve of Eratosthenes |
| 231 | Power of Two | n and (n-1) == 0 |
| 263 | Ugly Number | Divide by 2, 3, 5 |
| 292 | Nim Game | n mod 4 != 0 |
| 338 | Counting Bits | dp[i] = dp[i>>1] + (i and 1) |
| 342 | Power of Four | n and (n-1)==0 and n mod 3==1 |
| 365 | Water and Jug | GCD Bezout identity |
| 372 | Super Pow | Modular exponentiation |
| 412 | Fizz Buzz | Modulo |
| 441 | Arranging Coins | Quadratic formula |
| 462 | Min Moves II | Median minimizes absolute deviation |
| 492 | Construct Rectangle | Sqrt then iterate down |
| 509 | Fibonacci | DP or matrix exponentiation |
| 523 | Continuous Subarray Sum | Prefix mod hashmap |
| 628 | Max Product of Three | Sort + consider negatives |
| 812 | Largest Triangle Area | Convex hull or O(n^3) brute force |
| 878 | Nth Magical Number | Binary search + LCM inclusion-exclusion |
| 1175 | Prime Arrangements | Count primes, use factorial mod |
| 1201 | Ugly Number III | Inclusion-exclusion with LCM |
| 1492 | Kth Factor of n | Iterate to sqrt(n) |
| 1979 | Find GCD of Array | Min, max, gcd |
Common Pitfalls
- Overflow. Use
long longin C++; Python handles natively. In LCM always divide first. - Float comparison. Use
abs(a-b) < 1e-9, nota == b. - Fermat inverse. Only valid when modulus is prime — use Extended GCD otherwise.
- GCD of 0.
gcd(0, n) = n— handle carefully in LCM to avoid division by zero. - Sieve optimization. Start inner loop at
p*p, not2*p, to avoid redundant work. - nCr for large n. Always precompute factorials; never compute inline in a loop.
Interview Mindset
- Math problems often have O(1) formulas — look for the closed-form pattern first.
- Binary search on the answer works when feasibility is monotone.
- GCD/LCM often unlocks problems involving multiples and divisibility.
- XOR is the tool for parity, single-occurrence detection, and Nim-style games.
- When stuck, try small examples (n=1,2,3,4) and look for patterns in the sequence.
Key Takeaways
- The Sieve of Eratosthenes generates all primes up to n in O(n log log n) — the inner loop starts at
p*p, not2p. - GCD via the Euclidean algorithm runs in O(log n) and is the foundation of LCM, modular inverse, and CRT.
- Binary exponentiation computes
a^n mod min O(log n) by squaring at each bit of the exponent. - Fermat's little theorem gives modular inverse as
a^(m-2) mod m, but only when m is prime. - Precomputing factorials in O(n) enables O(1) nCr queries — essential for combinatorics problems.
- LCM overflow is avoided by dividing before multiplying:
a // gcd(a, b) * b. - SPF (smallest prime factor) sieve enables O(log n) factorization of any number after O(n log log n) preprocessing.
Advertisement
Related reading
String Algorithms — Master Recap and Pattern Cheatsheet6 min readTries — Master Recap and Interview Cheatsheet5 min readMissing Number — Gauss Formula and XOR Trick [LC 268]5 min readMinimum Moves to Equal Array Elements II — Why the Median Wins [LC 462]5 min readMax Points on a Line [Hard] — Slope Hashing with GCD [Google / Amazon]18 min readMissing Number — XOR Cancellation vs Gauss Sum Formula7 min read