Math / Number Theory
varies
Reach for the standard tool: Sieve of Eratosthenes, Euclid's gcd, fast power by squaring.
0/116 solved
Recognise it
The signal
Answer mod 1e9+7, primes/divisors/gcd, digits of a number, or huge n where only a formula is fast.
1Brute force
Simulate or loop up to n.
2The observation
Linear loops over huge ranges: closed forms, sieve, or binary exponentiation.
3Why it works
A problem-specific identity holds, e.g. a^b = (a^(b/2))^2 · a^(b mod 2).
Reach for it when
- +primes/divisors/gcd
- +huge n where only a formula is fast
- +digits of a number
Not when
- ×No identity appliesuse DP or search
Practice
- Palindrome NumberFoundationFoundationEasy
- Excel Sheet Column NumberApply it · Base conversion.Apply itEasy
- Pow(x, n)One change · Fast exponentiation.One changeMeta, GoogleMedium
- Count PrimesOne change · Sieve.One changeMedium
- Greatest Common Divisor of StringsTwists · GCD on strings.TwistsEasy
- Binomial CoefficientsBranches · nCr mod p, many queries.BranchesCSESMedium
- Counting DivisorsBranches · Divisor counts for many numbers.BranchesCSESMedium
- Prime MultiplesMastery checkMastery checkCSESMedium
- Happy NumberAdobe, AppleEasy
- Range Addition IIEasy
- Count Numbers with Unique DigitsMedium
- Stone GameMedium
Pitfalls
Classic bugs
- !Integer overflow before taking mod: reduce operands and multiply in 64-bit.
- !Negative exponents in pow: fast exponentiation assumes b >= 0; handle the sign separately.
Looks like it, isn't
- Happy Number needs Fast & Slow Pointers
Why
The question is whether an iterated function cycles; Floyd detects it without a set. source ↗
Go deepervariants and techniques · 13 combinations · resources
Variants and techniques
- Binary Exponentiation (fast power)Compute a^n (mod m) in O(log n) by squaring and multiplying on set bits; generalises to matrices and any associative operation.
- Sieve of Eratosthenes / Smallest Prime FactorMark composites up to N in O(N log log N) (or store smallest prime factors) to list primes and factorise many numbers fast.
- GCD / LCM & Euclidgcd(a, b) = gcd(b, a mod b) in O(log); lcm = a / gcd * b; extended Euclid solves ax + by = g and modular inverses.
- Combinatorics mod p (nCr, Catalan, stars and bars)Count arrangements with factorials and inverse factorials mod p, stars and bars, Catalan numbers, and bijections.
- Combinatorial Game Theory (minimax, Nim, Sprague-Grundy)Classify positions as winning/losing by DP over states, and combine independent games with Grundy numbers XORed together.
- Computational Geometry PrimitivesUse integer cross products for orientation, segment intersection, polygon area (shoelace), and point-in-polygon tests.
- Probability & Expected-Value DP (linearity of expectation)Interview · hardCompute probabilities or expectations by DP over states. Use linearity of expectation to split a hard expectation into a sum of easy per-element or per-pair indicator probabilities.
- Gaussian Elimination (mod p / reals) & Matrix-Tree TheoremCP 2000Solve n linear equations, or compute a rank or determinant, in O(n^3) by row reduction. Kirchhoff's theorem counts spanning trees as any cofactor of the Laplacian. Expected-value systems on cyclic state graphs are also solved this way.
- FFT / NTT Convolution (and Walsh-Hadamard)CP 2400+Multiply polynomials (convolve count arrays) in O(n log n). Use it whenever the answer is c[k] = sum of a[i]*b[k-i]: counting pair sums, matching with wildcards or mismatches, polynomial products. XOR/AND/OR convolutions use the Walsh-Hadamard transform.
- Invariants & Parity ArgumentsInterview · mediumFind a quantity that every move preserves (parity, sum mod k, XOR, the order of some subset) or always changes in one direction (a monovariant). It settles reachability or the winner in O(1) and replaces search.
- Harmonic Lemma & Quotient BlocksCP 1600Two counting facts. Looping over all multiples of every d <= n costs n/1 + n/2 + ... = O(n log n). And floor(n/i) takes only O(sqrt n) distinct values, each on a contiguous block of i, so a sum of f(floor(n/i)) costs O(sqrt n).
Combinations
Mobius Inversion & Multiplicative Functions+Sieve of Eratosthenes / Smallest Prime Factor+Combinatorics mod p (nCr, Catalan, stars and bars)
count pairs/subsequences with gcd 1 (or gcd exactly g), values <= 1e6
- Mobius Inversion & Multiplicative Functions:
- invert 'divisible by d' counts into 'gcd exactly 1'
- Sieve of Eratosthenes / Smallest Prime Factor:
- a linear sieve for mu (and the multiples counts)
- Combinatorics mod p (nCr, Catalan, stars and bars):
- count pairs C(c_d, 2) or subsets 2^c_d - 1 from c_d multiples
FFT / NTT Convolution (and Walsh-Hadamard)+String Matching (KMP / Z / Rabin-Karp)
pattern matching with wildcards, or counting mismatches/near-matches for every alignment
- FFT / NTT Convolution (and Walsh-Hadamard):
- for each alphabet letter, convolve the indicator arrays to count matches at every shift
- String Matching (KMP / Z / Rabin-Karp):
- the matching-per-shift question
FFT / NTT Convolution (and Walsh-Hadamard)+Prefix Sum
for every k, the number of subarrays with exactly k elements satisfying a predicate
- FFT / NTT Convolution (and Walsh-Hadamard):
- convolve the count array with its reverse to count subarrays with exactly k good elements, for all k
- Prefix Sum:
- count the prefixes having each number of 'good' elements
Few Distinct Subarray OR / AND / GCD Values+GCD / LCM & Euclid+Hash Map / Hash Set Lookup
the number of subarrays whose gcd equals x, for many x
- Few Distinct Subarray OR / AND / GCD Values:
- O(log V) (gcd, count) pairs per right end
- GCD / LCM & Euclid:
- the gcd as j moves left only drops to a divisor
- Hash Map / Hash Set Lookup:
- global count of subarrays per gcd value
Combinatorial Game Theory (minimax, Nim, Sprague-Grundy)+Bitmask DP
two players pick from a small pool (n <= 20) without replacement
- Combinatorial Game Theory (minimax, Nim, Sprague-Grundy):
- a state is winning if some move leads to a losing state
- Bitmask DP:
- the set of used numbers is the state
Probability & Expected-Value DP (linearity of expectation)+1D / Fibonacci-style+Sliding Window
probability over a running total with uniform draws and a stopping threshold
- Probability & Expected-Value DP (linearity of expectation):
- P(i) = (1/W) * sum of P(i - k) over k = 1..W
- 1D / Fibonacci-style:
- the probability DP over points
- Sliding Window:
- keep that sum in O(1) per step
Probability & Expected-Value DP (linearity of expectation)+Contribution Technique (sum over all subarrays/pairs)
expected number of inversions / empty squares / matches
- Probability & Expected-Value DP (linearity of expectation):
- linearity: sum the indicator probabilities
- Contribution Technique (sum over all subarrays/pairs):
- split the total into per-pair or per-square indicators
Probability & Expected-Value DP (linearity of expectation)+Gaussian Elimination (mod p / reals) & Matrix-Tree Theorem
expected steps of a random walk with self-loops or sideways moves
- Probability & Expected-Value DP (linearity of expectation):
- E[state] = 1 + sum of p * E[next]
- Gaussian Elimination (mod p / reals) & Matrix-Tree Theorem:
- solve the system when states reference each other
DP on Trees+Combinatorics mod p (nCr, Catalan, stars and bars)
count the orders in which tree nodes can be added parent-first (or BST insert orders)
- DP on Trees:
- subtree sizes and the ways for each child
- Combinatorics mod p (nCr, Catalan, stars and bars):
- interleave the children's orders with multinomials, i.e. n! / product of subtree sizes
Count Ways to Build Rooms in an Ant ColonyNumber of Ways to Reorder Array to Get Same BST
Dijkstra (Weighted Shortest Path)+Invariants & Parity Arguments
grid with per-cell earliest-entry times where you may not stand still
- Dijkstra (Weighted Shortest Path):
- earliest arrival time per cell
- Invariants & Parity Arguments:
- waiting is only possible by stepping back and forth, which adds 2, so the arrival parity is fixed
Gaussian Elimination (mod p / reals) & Matrix-Tree Theorem+Lagrange Interpolation
count spanning trees sharing exactly k edges with a given tree, n <= 100
- Gaussian Elimination (mod p / reals) & Matrix-Tree Theorem:
- matrix-tree determinants for spanning trees with weighted edges
- Lagrange Interpolation:
- recover the polynomial in x from n evaluations
Probability & Expected-Value DP (linearity of expectation)+Tree DFS (Paths & Recursion)
probability that a random walk on a tree is at vertex v at time t
- Probability & Expected-Value DP (linearity of expectation):
- the probability multiplies by 1/(#unvisited children) at each step
- Tree DFS (Paths & Recursion):
- walk from the root with depth/time
Harmonic Lemma & Quotient Blocks+Prefix Sum
sum over pairs of floor(a_i / a_j) with values <= 1e5
- Harmonic Lemma & Quotient Blocks:
- for each divisor value d and each multiple k*d, the count of x in [k*d, (k+1)*d) contributes k
- Prefix Sum:
- counts of values in a range in O(1)