Every formula and identity worth knowing for CP, grouped by topic and numbered for quick reference. No explanations here. Each topicβs notes cover the details.
Sums and Series
- for
- for
- for
- (sum of falling powers: )
- ,
- (sieve is )
- Faulhaber: (Bernoulli numbers, )
- is a polynomial of degree in (use Lagrange interpolation on points)
- Abel summation: ,
- Sum of all subarray sums:
- Sum of all pairwise (sorted):
- Sum over all subsets of the subset sums:
Floor, Ceil and Division
- for
- takes at most distinct values. For a block starting at , the last index with the same value is
- Hermite:
- is computed in by the floor-sum (Euclid-like) recursion
- Number of multiples of in :
- : start from
sqrtl(n), then adjust by while the square overshoots or undershoots
GCD and Divisibility
- ,
- BΓ©zout:
- is solvable iff . General solution:
- ,
- of an array is preserved under adjacent differences
- Prefix gcds take at most distinct values
- (grows like )
- Chicken McNugget: the largest number not representable as (, ) is . Exactly numbers are not representable
- Euclidβs lemma: for prime
Divisor Functions
- If :
- Product of divisors:
- ,
- Number of divisors of is at most about , typically
Eulerβs Totient and MΓΆbius
- , is multiplicative
- ,
- for
- MΓΆbius inversion:
- Superset form:
- Dirichlet convolution: . Identities: , , ,
- , probability two random integers are coprime is
- Duβs sieve: (with ),
Modular Arithmetic
- Fermat: for prime
- Euler: for
- Extended Euler: for (any ) β power towers
- Wilson:
- Inverses in :
- CRT: for coprime , ,
- CRT for non-coprime : solvable iff , result is modulo
- Euler criterion:
- Number of quadratic residues mod odd prime (excluding 0):
- ,
- Quadratic reciprocity:
- A primitive root exists modulo . There are of them
- is a primitive root mod iff for every prime
- has solutions if , else 0
- , safe mod:
((a % m) + m) % m - NTT-friendly primes: (root 3), (root 3), (root 3)
- Common hashing primes: , , (Mersenne)
Primes
- . , ,
- Prime gaps below are at most 282, below at most 1442
- Deterministic MillerβRabin for 64-bit: bases , or the first 12 primes
- Bertrand: there is a prime in for
- Goldbach (verified far beyond ): every even is a sum of two primes
- Every prime is
- Legendre: exponent of in is
- Kummer: = number of carries when adding and in base
- Lifting the exponent: for odd , :
- Trailing zeros of :
- Fermatβs two squares: is a sum of two squares iff every prime appears with an even exponent
- Four squares (Lagrange): every is a sum of four squares. Three squares works unless
Binomial Coefficients
- ,
- Pascal:
- ,
- ,
- for
- ,
- Hockey stick:
- Vandermonde:
- (shallow diagonals of Pascalβs triangle)
- Lucas: (base- digits)
- is odd iff (i.e. as bitmasks)
- Binomial theorem:
- Multinomial:
- ,
- Central binomial:
Counting
- Stars and bars: nonnegative solutions of : . Positive:
- With upper bounds :
- Multisets of size from types:
- Lattice paths :
- Paths not crossing (reflection): . Paths to that touch : reflect the start point across it
- Ballot problem: sequences with up-steps, down-steps () staying positive:
- Permutations of a multiset:
- -permutations:
- Circular arrangements: , necklaces up to reflection too:
- Derangements: ,
- Inclusionβexclusion:
- Surjections :
- Functions : . Injections:
- Subsets of size with no two adjacent from :
- Burnside: number of orbits
- Necklaces of length with colors (rotation):
- Bracelets (rotation + reflection): for even (with = necklaces), for odd
- PΓ³lya: , = number of cycles of
- Labeled graphs on vertices:
- Cayley: labeled trees on vertices: . Rooted labeled forests with given roots:
- Spanning trees of :
- Kirchhoff: number of spanning trees = any cofactor of the Laplacian
- LGV lemma: non-intersecting path systems
- Number of perfect matchings of :
- Involutions:
- Permutations with inversions: . Total inversions over all permutations:
- Expected number of fixed points of a random permutation: . Expected cycles:
Special Numbers
- Catalan: , ,
- Catalan counts: balanced parentheses, binary trees with nodes, full binary trees with leaves, triangulations of an -gon, Dyck paths, non-crossing partitions, monotone lattice paths under the diagonal, 231-avoiding permutations
- : 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796
- Super Catalan / SchrΓΆder: (1, 2, 6, 22, 90)
- Motzkin: (1, 1, 2, 4, 9, 21, 51)
- Stirling 1st kind (unsigned, permutations with cycles): ,
- Stirling 2nd kind (partitions into nonempty sets):
- ,
- Bell: , (1, 1, 2, 5, 15, 52, 203, 877)
- Partitions of : (pentagonal theorem).
- Partitions into distinct parts = partitions into odd parts
- Partitions of into at most parts = partitions of into parts of size at most :
- Eulerian numbers (permutations with ascents):
- Narayana: (Dyck paths with peaks)
- Fibonacci: , ,
- Doubling: ,
- Cassini:
- , ,
- Pisano period for (): . if , if
- Zeckendorf: every positive integer is a unique sum of non-consecutive Fibonacci numbers
- Bernoulli: for ,
- Harmonic: ; Wolstenholme: for
Generating Functions
- ,
- , ,
- Catalan: ,
- Fibonacci:
- Partitions: . Distinct parts:
- EGF of set partitions: . Derangements: . Involutions:
- Exponential formula: connected structures all structures
- Product of OGFs = convolution. Product of EGFs = binomial convolution
- Linear recurrence of order rational GF , , . The -th term is (BostanβMori, )
- Multiplying by maps . Multiplying by takes prefix sums
Probability and Expectation
- Linearity: always. if independent
- for
- ,
- Geometric (success prob. ): ,
- Binomial: ,
- Coupon collector:
- Birthday: collision expected after draws.
- Bayes:
- Total probability:
- Indicator trick:
- Expected maximum of i.i.d. : . Expected -th smallest:
- Gamblerβs ruin (fair): probability of reaching from is . Biased with :
- Random walk on a line: expected time to hit from 0 is
- Markov: . Chebyshev:
- Expected value mod :
- Expected steps in a Markov chain: (solve the linear system, or DP on a DAG)
- Probability that a random permutation has a given -cycle structure:
Linear Algebra and Matrices
- , ,
- Swapping rows flips the sign, adding a multiple of a row keeps it, scaling a row by multiplies it by
- ,
- inverse:
- Rankβnullity: (columns)
- Number of solutions of over (if consistent):
- Linear recurrence companion matrix power: , or Kitamasa
- Number of walks of length from to :
- Shortest walk with exactly edges: min-plus matrix power
- CayleyβHamilton:
- Vandermonde determinant:
- XOR basis: size . A span of basis vectors has elements. Every value in the span is produced by subsets
Bit Manipulation
- and
- clears the lowest set bit. isolates it
- sets the lowest zero bit. clears trailing ones
- is a power of 2 iff and
- for
- , with from formula 217
- (or 0 if )
- Submask enumeration:
for (s = m; s; s = (s - 1) & m). Over all masks this is in total - Gosperβs hack (next mask with the same popcount):
c = x & -x, r = x + c, x = (((r ^ x) >> 2) / c) | r - Gray code: . Inverse: prefix XOR of the bits from the top
- Bits are independent: , = count with bit set
- Sum of over all subarrays: per bit, count maximal runs of 1s. A run of length in bit contributes
- SOS DP: in . Inverse (MΓΆbius) with alternating signs
- Subset convolution: with ranked zeta transforms
- XOR convolution via FWHT: , inverse divides by
__builtin_popcountll,__builtin_clzll(undefined for 0),__builtin_ctzll,__lg(x),std::bit_width
Graph Theory
- Handshake: , so the number of odd-degree vertices is even
- A tree has edges. A forest with components has edges
- Euler path exists iff connected (ignoring isolated vertices) and 0 or 2 odd vertices. Directed: everywhere, except at most one vertex with and one with
- Eulerβs formula (planar, connected): . Simple planar: , bipartite planar:
- KΕnig (bipartite): max matching min vertex cover. Max independent set max matching
- Hall: a matching saturating exists iff for all
- Gallai: in any graph without isolated vertices, and (max matching + min edge cover)
- Dilworth: in a poset, min chain cover max antichain. Min path cover in a DAG max matching of the split graph
- Mirsky: min antichain cover longest chain (LIS length duality)
- Max-flow min-cut
- ErdΕsβGallai: is graphic iff the sum is even and for all
- TurΓ‘n: a -free graph has at most edges
- Bipartite iff there is no odd cycle
- Number of edges in a DAGβs transitive closure: compute with bitsets in
- Tree diameter: BFS from any vertex to the farthest , then BFS from
- Centers: 1 or 2. Centroids: 1 or 2. The centroidβs largest remaining component has vertices
- PrΓΌfer sequence: length , vertex appears times trees with given degrees:
- Number of distinct paths in a tree: . Sum of all pairwise distances:
- Brooks: unless is complete or an odd cycle. Vizing:
- Chromatic polynomial of a tree: . Cycle:
- Ramsey: ,
- Small-to-large merging: every element moves times
- HLD: any root-to-leaf path crosses light edges
Game Theory
- Nim: the first player wins iff
- SpragueβGrundy: . Sum of games: XOR of Grundy values
- Misère Nim: if all piles , the first player wins iff the number of piles is even. Otherwise as normal Nim
- Staircase Nim: equivalent to Nim on the odd-indexed steps
- Bash game (take ): lose iff
- Wythoff: losing positions are
- Mooreβs Nim (take from up to piles): lose iff every bitβs count is
- Subtraction game with set : Grundy values are eventually periodic
- Green Hackenbush on trees: (colon principle)
- Chomp, Hex: the first player wins (strategy stealing)
Geometry
- Cross product: (positive is counter-clockwise from )
- Dot product:
- Shoelace:
- Pick: . Boundary points on a segment:
- Triangle: (Heron),
- Circumradius , inradius
- Law of sines: . Law of cosines:
- Distance from point to line :
- Line : distance from is
- Rotation by :
- Line intersection:
- Polygon centroid:
- Circle: area , sector , segment , chord
- Sphere: , . Cap of height :
- Cone: . Cylinder:
- Great-circle distance:
- Manhattan Chebyshev: turns into
- Convex hull of random points in a square has vertices. Lattice points of a convex polygon inside : hull vertices
- Number of regions formed by lines in general position: . Circle with points, all chords:
- 3D: , volume of tetrahedron
Strings
- is a period of iff has a border of length . The smallest period is
- is a power of a block iff divides
- FineβWilf: periods with is a period
- Number of distinct substrings in a suffix automaton
- A string has at most distinct palindromic substrings (eertree has nodes)
- Polynomial hash collision probability for two fixed strings: . Among strings: about
- Number of runs in a string (runs theorem)
- Lyndon factorization is unique (ChenβFoxβLyndon). Duval finds it in
- Necklace (minimal rotation) via Booth or Duval on
Complexity Limits
- Roughly simple operations per second
- : Β· : Β· : meet in the middle Β· : Β· : Β· : Β· : Β· : Β· larger: or
int,long long,__int128doublehas a 53-bit mantissa (~15β16 digits),long double64-bit (~18β19 digits)- , , ,
- , , , (the largest fitting in
long long) - ,
- Memory:
intMB, avector<int>of size is 256 MB
Small Tricks
- Swap without temp:
a ^= b, b ^= a, a ^= b - Average without overflow:
l + (r - l) / 2 - Round-up division for nonnegative values:
(a + b - 1) / b. Floor division for negative numerators:a / b - ((a % b != 0) && ((a < 0) != (b < 0))) - Overflow-safe
a * b % mfor 64-bit:(__int128)a * b % m - Compare fractions (for ) with
a * d < c * b - Compare vs by squaring twice, never with floating point near equality
- Count pairs with sum divisible by : bucket by , pair with
- Number of subarrays with sum : prefix sums + hashmap of counts
- Subarrays with XOR : prefix XOR + hashmap
- For βminimize the maximumβ, binary search the answer. For βmaximize the minimumβ, likewise
- Contribution technique: count how many times each element is the min/max with monotonic stacks:
- ,
- with ,
- Median minimizes . Mean minimizes
- Sorting by or by comparators (exchange argument): put before iff
- Coordinates on a grid: , 4-neighbours via
dr = {-1,0,1,0}, dc = {0,1,0,-1} - Random seed:
mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()) - Anti-hash for
unordered_map: splitmix64 with a random offset - Iterating over all pairs with up to costs
- Two sorted arrays: the -th smallest of their union in by binary searching how many come from the first
Inequalities and Approximations
- AMβGMβHM: for , equality iff all equal
- CauchyβSchwarz:
- Jensen: for convex , (reverse for concave )
- Bernoulliβs inequality: for and (or ); reversed for
- Triangle inequality: ;
- Stirlingβs approximation: , i.e.
- Power-mean inequality: for , (generalises AMβGM, taking as the geometric mean)
- Quadratic formula: ; integer roots require a perfect square
Polynomials, Roots and Symmetric Functions
- Vietaβs formulas: for , the elementary symmetric function (sum of roots , product )
- Newtonβs identities: power sums relate to elementary symmetric by β converts between a polynomialβs coefficients and its rootsβ power sums without finding the roots
- Cramerβs rule: for with , where replaces column of with
- Trace and eigenvalues: , , both summed/multiplied with multiplicity
- Discriminant of is ; of a general polynomial, (resultant with its derivative), zero iff has a repeated root
More Probability
- Variance of a sum: , (reduces to the independent-sum case when )
- Hypergeometric (draw without replacement from with successes): ,
- Poisson(): , ; sum of independent Poissons is Poisson with summed rates
- Union bound: (no independence needed, slack when events overlap a lot)
More Number Theory
- Pellβs equation ( not a perfect square): the fundamental solution comes from the continued fraction of ; all solutions are with , i.e.
- Continued fraction convergents of : , (); , and is the best rational approximation to the continued fractionβs value among fractions with denominator
- -binomial coefficient (Gaussian binomial): , counts -dimensional subspaces of ; reduces to as
- MΓΆbius function closed form: ; if is a product of distinct primes; if any prime divides more than once (not squarefree)
More Graph Theory
- BEST theorem: the number of Eulerian circuits of a connected directed graph with every is , where is the number of arborescences oriented into any fixed vertex (same for every choice of ) β see Matrix-Tree for and Euler Tours for the full count
- ErdΕsβGallai / handshake extension: the number of edges in any simple graph is at most ; a graph is self-complementary only if is even