Modular Arithmetic and Counting

Handle huge answers 'modulo 1e9+7' correctly, compute fast powers and inverses, and count arrangements with nCr and basic combinatorics.

Intermediate · about 6 hours · difficulty 3/5

Learn first: Complexity Analysis

Many problems ask for an answer "modulo 10^9 + 7" because the true count is astronomically large. You need to know which operations are safe under a modulus and how to compute counts efficiently.

Modular rules

  • (a + b) mod m, (a - b) mod m and (a * b) mod m can be applied at every step. For subtraction add m before taking mod to avoid negatives: ((a - b) % m + m) % m.
  • Division is not direct. Multiply by the modular inverse instead. When m is prime, inverse of a is a^(m-2) mod m (Fermat's little theorem).
  • Multiply in 64-bit: two values below 1e9+7 multiply to about 1e18, which fits in long long but not in int.

Fast exponentiation

Binary exponentiation computes a^b in O(log b) by squaring: if the current bit of b is set, multiply the result by a, then square a and shift b right. It powers modular inverses, matrix exponentiation and hashing.

Counting basics

  • Permutations n!, combinations nCr = n! / (r! (n-r)!).
  • For many nCr queries, precompute factorials and inverse factorials up to n in O(n), then each query is O(1).
  • Pascal's triangle C[n][r] = C[n-1][r-1] + C[n-1][r] works for small n without inverses.
  • Stars and bars, inclusion-exclusion and the pigeonhole principle appear in medium-hard problems.

Good enough to move on: you can write modpow and a precomputed nCr table without bugs and explain why the subtraction fix is needed.

Key concepts

  • Mod rules for +, -, *
  • Binary exponentiation
  • Modular inverse via Fermat
  • Factorial and inverse factorial tables
  • nCr and Pascal's triangle
  • Inclusion-exclusion
  • Stars and bars
  • Extended Euclid for inverses: When m is not prime

Mini project

Implement modpow and an nCr helper with precomputed factorials, then solve: Pow(x, n), Count Good Numbers, Unique Paths via nCr, CSES Binomial Coefficients, CSES Exponentiation II, and a 'count strings of length n with no two adjacent equal chars' problem mod 1e9+7.

Check yourself

Why can you not compute (a / b) mod m as (a mod m) / (b mod m), and what do you do instead when m is prime?

Free resources