Math and Number Theory — Master Recap and Interview Cheatsheet

Sanjeev SharmaSanjeev Sharma
6 min read

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 PatternAlgorithmComplexity
All primes up to nSieve of EratosthenesO(n log log n)
Factorize one numberTrial divisionO(sqrt n)
Factorize many numbersSPF sieve + lookupO(n log log n) + O(log n)
GCD of two numbersEuclideanO(log min)
Modular inverse (prime mod)Fermat little theoremO(log mod)
Modular inverse (any mod)Extended GCDO(log a)
a^n mod mBinary exponentiationO(log n)
nCr mod primePrecomputed factorialsO(n) build, O(1) query
Fibonacci(10^18)Matrix exponentiationO(log n)
Count divisorsFactor then multiply exponentsO(sqrt n)
Sum of divisorsFactor then formulaO(sqrt n)
Euler totient(n)Trial factorizationO(sqrt n)
All totients to nSieve variantO(n log log n)
Nim gameXOR all pilesO(n)
System of modular equationsCRTO(k log m)
Range queriesSqrt decompositionO(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 s

Complexity Summary

AlgorithmTimeSpace
SieveO(n log log n)O(n)
GCDO(log n)O(1)
Fast PowO(log n)O(1)
nCr precomputedO(n) build, O(1) queryO(n)
Prime factorizeO(sqrt n)O(log n)
Extended GCDO(log min(a,b))O(1)

Top 25 Math/Number Theory LeetCode Problems

LCProblemKey Technique
50Pow(x,n)Binary exponentiation
69Sqrt(x)Binary search
149Max Points on a LineGCD slope normalization
172Factorial Trailing ZerosCount factors of 5
204Count PrimesSieve of Eratosthenes
231Power of Twon and (n-1) == 0
263Ugly NumberDivide by 2, 3, 5
292Nim Gamen mod 4 != 0
338Counting Bitsdp[i] = dp[i>>1] + (i and 1)
342Power of Fourn and (n-1)==0 and n mod 3==1
365Water and JugGCD Bezout identity
372Super PowModular exponentiation
412Fizz BuzzModulo
441Arranging CoinsQuadratic formula
462Min Moves IIMedian minimizes absolute deviation
492Construct RectangleSqrt then iterate down
509FibonacciDP or matrix exponentiation
523Continuous Subarray SumPrefix mod hashmap
628Max Product of ThreeSort + consider negatives
812Largest Triangle AreaConvex hull or O(n^3) brute force
878Nth Magical NumberBinary search + LCM inclusion-exclusion
1175Prime ArrangementsCount primes, use factorial mod
1201Ugly Number IIIInclusion-exclusion with LCM
1492Kth Factor of nIterate to sqrt(n)
1979Find GCD of ArrayMin, max, gcd

Common Pitfalls

  1. Overflow. Use long long in C++; Python handles natively. In LCM always divide first.
  2. Float comparison. Use abs(a-b) < 1e-9, not a == b.
  3. Fermat inverse. Only valid when modulus is prime — use Extended GCD otherwise.
  4. GCD of 0. gcd(0, n) = n — handle carefully in LCM to avoid division by zero.
  5. Sieve optimization. Start inner loop at p*p, not 2*p, to avoid redundant work.
  6. 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, not 2p.
  • 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 m in 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

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro

Related reading