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

  1. for
  2. for
  3. for
  4. (sum of falling powers: )
  5. ,
  6. (sieve is )
  7. Faulhaber: (Bernoulli numbers, )
  8. is a polynomial of degree in (use Lagrange interpolation on points)
  9. Abel summation: ,
  10. Sum of all subarray sums:
  11. Sum of all pairwise (sorted):
  12. Sum over all subsets of the subset sums:

Floor, Ceil and Division

  1. for
  2. takes at most distinct values. For a block starting at , the last index with the same value is
  3. Hermite:
  4. is computed in by the floor-sum (Euclid-like) recursion
  5. Number of multiples of in :
  6. : start from sqrtl(n), then adjust by while the square overshoots or undershoots

GCD and Divisibility

  1. ,
  2. BΓ©zout:
  3. is solvable iff . General solution:
  4. ,
  5. of an array is preserved under adjacent differences
  6. Prefix gcds take at most distinct values
  7. (grows like )
  8. Chicken McNugget: the largest number not representable as (, ) is . Exactly numbers are not representable
  9. Euclid’s lemma: for prime

Divisor Functions

  1. If :
  2. Product of divisors:
  3. ,
  4. Number of divisors of is at most about , typically

Euler’s Totient and MΓΆbius

  1. , is multiplicative
  2. ,
  3. for
  4. MΓΆbius inversion:
  5. Superset form:
  6. Dirichlet convolution: . Identities: , , ,
  7. , probability two random integers are coprime is
  8. Du’s sieve: (with ),

Modular Arithmetic

  1. Fermat: for prime
  2. Euler: for
  3. Extended Euler: for (any ) β€” power towers
  4. Wilson:
  5. Inverses in :
  6. CRT: for coprime , ,
  7. CRT for non-coprime : solvable iff , result is modulo
  8. Euler criterion:
  9. Number of quadratic residues mod odd prime (excluding 0):
  10. ,
  11. Quadratic reciprocity:
  12. A primitive root exists modulo . There are of them
  13. is a primitive root mod iff for every prime
  14. has solutions if , else 0
  15. , safe mod: ((a % m) + m) % m
  16. NTT-friendly primes: (root 3), (root 3), (root 3)
  17. Common hashing primes: , , (Mersenne)

Primes

  1. . , ,
  2. Prime gaps below are at most 282, below at most 1442
  3. Deterministic Miller–Rabin for 64-bit: bases , or the first 12 primes
  4. Bertrand: there is a prime in for
  5. Goldbach (verified far beyond ): every even is a sum of two primes
  6. Every prime is
  7. Legendre: exponent of in is
  8. Kummer: = number of carries when adding and in base
  9. Lifting the exponent: for odd , :
  10. Trailing zeros of :
  11. Fermat’s two squares: is a sum of two squares iff every prime appears with an even exponent
  12. Four squares (Lagrange): every is a sum of four squares. Three squares works unless

Binomial Coefficients

  1. ,
  2. Pascal:
  3. ,
  4. ,
  5. for
  6. ,
  7. Hockey stick:
  8. Vandermonde:
  9. (shallow diagonals of Pascal’s triangle)
  10. Lucas: (base- digits)
  11. is odd iff (i.e. as bitmasks)
  12. Binomial theorem:
  13. Multinomial:
  14. ,
  15. Central binomial:

Counting

  1. Stars and bars: nonnegative solutions of : . Positive:
  2. With upper bounds :
  3. Multisets of size from types:
  4. Lattice paths :
  5. Paths not crossing (reflection): . Paths to that touch : reflect the start point across it
  6. Ballot problem: sequences with up-steps, down-steps () staying positive:
  7. Permutations of a multiset:
  8. -permutations:
  9. Circular arrangements: , necklaces up to reflection too:
  10. Derangements: ,
  11. Inclusion–exclusion:
  12. Surjections :
  13. Functions : . Injections:
  14. Subsets of size with no two adjacent from :
  15. Burnside: number of orbits
  16. Necklaces of length with colors (rotation):
  17. Bracelets (rotation + reflection): for even (with = necklaces), for odd
  18. PΓ³lya: , = number of cycles of
  19. Labeled graphs on vertices:
  20. Cayley: labeled trees on vertices: . Rooted labeled forests with given roots:
  21. Spanning trees of :
  22. Kirchhoff: number of spanning trees = any cofactor of the Laplacian
  23. LGV lemma: non-intersecting path systems
  24. Number of perfect matchings of :
  25. Involutions:
  26. Permutations with inversions: . Total inversions over all permutations:
  27. Expected number of fixed points of a random permutation: . Expected cycles:

Special Numbers

  1. Catalan: , ,
  2. 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
  3. : 1, 1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796
  4. Super Catalan / SchrΓΆder: (1, 2, 6, 22, 90)
  5. Motzkin: (1, 1, 2, 4, 9, 21, 51)
  6. Stirling 1st kind (unsigned, permutations with cycles): ,
  7. Stirling 2nd kind (partitions into nonempty sets):
  8. ,
  9. Bell: , (1, 1, 2, 5, 15, 52, 203, 877)
  10. Partitions of : (pentagonal theorem).
  11. Partitions into distinct parts = partitions into odd parts
  12. Partitions of into at most parts = partitions of into parts of size at most :
  13. Eulerian numbers (permutations with ascents):
  14. Narayana: (Dyck paths with peaks)
  15. Fibonacci: , ,
  16. Doubling: ,
  17. Cassini:
  18. , ,
  19. Pisano period for (): . if , if
  20. Zeckendorf: every positive integer is a unique sum of non-consecutive Fibonacci numbers
  21. Bernoulli: for ,
  22. Harmonic: ; Wolstenholme: for

Generating Functions

  1. ,
  2. , ,
  3. Catalan: ,
  4. Fibonacci:
  5. Partitions: . Distinct parts:
  6. EGF of set partitions: . Derangements: . Involutions:
  7. Exponential formula: connected structures all structures
  8. Product of OGFs = convolution. Product of EGFs = binomial convolution
  9. Linear recurrence of order rational GF , , . The -th term is (Bostan–Mori, )
  10. Multiplying by maps . Multiplying by takes prefix sums

Probability and Expectation

  1. Linearity: always. if independent
  2. for
  3. ,
  4. Geometric (success prob. ): ,
  5. Binomial: ,
  6. Coupon collector:
  7. Birthday: collision expected after draws.
  8. Bayes:
  9. Total probability:
  10. Indicator trick:
  11. Expected maximum of i.i.d. : . Expected -th smallest:
  12. Gambler’s ruin (fair): probability of reaching from is . Biased with :
  13. Random walk on a line: expected time to hit from 0 is
  14. Markov: . Chebyshev:
  15. Expected value mod :
  16. Expected steps in a Markov chain: (solve the linear system, or DP on a DAG)
  17. Probability that a random permutation has a given -cycle structure:

Linear Algebra and Matrices

  1. , ,
  2. Swapping rows flips the sign, adding a multiple of a row keeps it, scaling a row by multiplies it by
  3. ,
  4. inverse:
  5. Rank–nullity: (columns)
  6. Number of solutions of over (if consistent):
  7. Linear recurrence companion matrix power: , or Kitamasa
  8. Number of walks of length from to :
  9. Shortest walk with exactly edges: min-plus matrix power
  10. Cayley–Hamilton:
  11. Vandermonde determinant:
  12. XOR basis: size . A span of basis vectors has elements. Every value in the span is produced by subsets

Bit Manipulation

  1. and
  2. clears the lowest set bit. isolates it
  3. sets the lowest zero bit. clears trailing ones
  4. is a power of 2 iff and
  5. for
  6. , with from formula 217
  7. (or 0 if )
  8. Submask enumeration: for (s = m; s; s = (s - 1) & m). Over all masks this is in total
  9. Gosper’s hack (next mask with the same popcount): c = x & -x, r = x + c, x = (((r ^ x) >> 2) / c) | r
  10. Gray code: . Inverse: prefix XOR of the bits from the top
  11. Bits are independent: , = count with bit set
  12. Sum of over all subarrays: per bit, count maximal runs of 1s. A run of length in bit contributes
  13. SOS DP: in . Inverse (MΓΆbius) with alternating signs
  14. Subset convolution: with ranked zeta transforms
  15. XOR convolution via FWHT: , inverse divides by
  16. __builtin_popcountll, __builtin_clzll (undefined for 0), __builtin_ctzll, __lg(x) , std::bit_width

Graph Theory

  1. Handshake: , so the number of odd-degree vertices is even
  2. A tree has edges. A forest with components has edges
  3. 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
  4. Euler’s formula (planar, connected): . Simple planar: , bipartite planar:
  5. KΕ‘nig (bipartite): max matching min vertex cover. Max independent set max matching
  6. Hall: a matching saturating exists iff for all
  7. Gallai: in any graph without isolated vertices, and (max matching + min edge cover)
  8. Dilworth: in a poset, min chain cover max antichain. Min path cover in a DAG max matching of the split graph
  9. Mirsky: min antichain cover longest chain (LIS length duality)
  10. Max-flow min-cut
  11. ErdΕ‘s–Gallai: is graphic iff the sum is even and for all
  12. TurΓ‘n: a -free graph has at most edges
  13. Bipartite iff there is no odd cycle
  14. Number of edges in a DAG’s transitive closure: compute with bitsets in
  15. Tree diameter: BFS from any vertex to the farthest , then BFS from
  16. Centers: 1 or 2. Centroids: 1 or 2. The centroid’s largest remaining component has vertices
  17. PrΓΌfer sequence: length , vertex appears times trees with given degrees:
  18. Number of distinct paths in a tree: . Sum of all pairwise distances:
  19. Brooks: unless is complete or an odd cycle. Vizing:
  20. Chromatic polynomial of a tree: . Cycle:
  21. Ramsey: ,
  22. Small-to-large merging: every element moves times
  23. HLD: any root-to-leaf path crosses light edges

Game Theory

  1. Nim: the first player wins iff
  2. Sprague–Grundy: . Sum of games: XOR of Grundy values
  3. Misère Nim: if all piles , the first player wins iff the number of piles is even. Otherwise as normal Nim
  4. Staircase Nim: equivalent to Nim on the odd-indexed steps
  5. Bash game (take ): lose iff
  6. Wythoff: losing positions are
  7. Moore’s Nim (take from up to piles): lose iff every bit’s count is
  8. Subtraction game with set : Grundy values are eventually periodic
  9. Green Hackenbush on trees: (colon principle)
  10. Chomp, Hex: the first player wins (strategy stealing)

Geometry

  1. Cross product: (positive is counter-clockwise from )
  2. Dot product:
  3. Shoelace:
  4. Pick: . Boundary points on a segment:
  5. Triangle: (Heron),
  6. Circumradius , inradius
  7. Law of sines: . Law of cosines:
  8. Distance from point to line :
  9. Line : distance from is
  10. Rotation by :
  11. Line intersection:
  12. Polygon centroid:
  13. Circle: area , sector , segment , chord
  14. Sphere: , . Cap of height :
  15. Cone: . Cylinder:
  16. Great-circle distance:
  17. Manhattan Chebyshev: turns into
  18. Convex hull of random points in a square has vertices. Lattice points of a convex polygon inside : hull vertices
  19. Number of regions formed by lines in general position: . Circle with points, all chords:
  20. 3D: , volume of tetrahedron

Strings

  1. is a period of iff has a border of length . The smallest period is
  2. is a power of a block iff divides
  3. Fine–Wilf: periods with is a period
  4. Number of distinct substrings in a suffix automaton
  5. A string has at most distinct palindromic substrings (eertree has nodes)
  6. Polynomial hash collision probability for two fixed strings: . Among strings: about
  7. Number of runs in a string (runs theorem)
  8. Lyndon factorization is unique (Chen–Fox–Lyndon). Duval finds it in
  9. Necklace (minimal rotation) via Booth or Duval on

Complexity Limits

  1. Roughly simple operations per second
  2. : Β· : Β· : meet in the middle Β· : Β· : Β· : Β· : Β· : Β· larger: or
  3. int , long long , __int128
  4. double has a 53-bit mantissa (~15–16 digits), long double 64-bit (~18–19 digits)
  5. , , ,
  6. , , , (the largest fitting in long long)
  7. ,
  8. Memory: int MB, a vector<int> of size is 256 MB

Small Tricks

  1. Swap without temp: a ^= b, b ^= a, a ^= b
  2. Average without overflow: l + (r - l) / 2
  3. Round-up division for nonnegative values: (a + b - 1) / b. Floor division for negative numerators: a / b - ((a % b != 0) && ((a < 0) != (b < 0)))
  4. Overflow-safe a * b % m for 64-bit: (__int128)a * b % m
  5. Compare fractions (for ) with a * d < c * b
  6. Compare vs by squaring twice, never with floating point near equality
  7. Count pairs with sum divisible by : bucket by , pair with
  8. Number of subarrays with sum : prefix sums + hashmap of counts
  9. Subarrays with XOR : prefix XOR + hashmap
  10. For β€œminimize the maximum”, binary search the answer. For β€œmaximize the minimum”, likewise
  11. Contribution technique: count how many times each element is the min/max with monotonic stacks:
  12. ,
  13. with ,
  14. Median minimizes . Mean minimizes
  15. Sorting by or by comparators (exchange argument): put before iff
  16. Coordinates on a grid: , 4-neighbours via dr = {-1,0,1,0}, dc = {0,1,0,-1}
  17. Random seed: mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count())
  18. Anti-hash for unordered_map: splitmix64 with a random offset
  19. Iterating over all pairs with up to costs
  20. Two sorted arrays: the -th smallest of their union in by binary searching how many come from the first

Inequalities and Approximations

  1. AM–GM–HM: for , equality iff all equal
  2. Cauchy–Schwarz:
  3. Jensen: for convex , (reverse for concave )
  4. Bernoulli’s inequality: for and (or ); reversed for
  5. Triangle inequality: ;
  6. Stirling’s approximation: , i.e.
  7. Power-mean inequality: for , (generalises AM–GM, taking as the geometric mean)
  8. Quadratic formula: ; integer roots require a perfect square

Polynomials, Roots and Symmetric Functions

  1. Vieta’s formulas: for , the elementary symmetric function (sum of roots , product )
  2. 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
  3. Cramer’s rule: for with , where replaces column of with
  4. Trace and eigenvalues: , , both summed/multiplied with multiplicity
  5. Discriminant of is ; of a general polynomial, (resultant with its derivative), zero iff has a repeated root

More Probability

  1. Variance of a sum: , (reduces to the independent-sum case when )
  2. Hypergeometric (draw without replacement from with successes): ,
  3. Poisson(): , ; sum of independent Poissons is Poisson with summed rates
  4. Union bound: (no independence needed, slack when events overlap a lot)

More Number Theory

  1. Pell’s equation ( not a perfect square): the fundamental solution comes from the continued fraction of ; all solutions are with , i.e.
  2. Continued fraction convergents of : , (); , and is the best rational approximation to the continued fraction’s value among fractions with denominator
  3. -binomial coefficient (Gaussian binomial): , counts -dimensional subspaces of ; reduces to as
  4. MΓΆbius function closed form: ; if is a product of distinct primes; if any prime divides more than once (not squarefree)

More Graph Theory

  1. 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
  2. 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