~/problems

Problems

Basics first, then the classics, then company-style assessments. Every problem has tests you run right here; multi-level ones unlock as you go. See the roadmap.

Number theory

Modular arithmetic

Fast exponentiation, Fermat inverses, nCr mod p with factorial tables.

Notes

Recognise it when: the problem says "answer modulo 10^9 + 7", or it involves huge powers or counting.

  • pow(a, b, m) is built in. Know how to write it by hand: square-and-multiply over the bits of b.
  • Inverse modulo a prime p: pow(a, p - 2, p) (Fermat). In Python 3.8+, pow(a, -1, m) works for any a coprime to m.
  • nCr mod p: precompute fact and inv_fact up to n. Then C = fact[n] * inv_fact[r] * inv_fact[n-r] % p.
  • Subtraction: (a - b) % m is always non-negative in Python.

Gotchas: apply % m after every multiplication (in other languages that's overflow, in Python it's speed). Division needs the inverse.

7 problems

Advanced & competitive

Number theory Modular arithmetic, primes, matrix powers.

Modular arithmetic

esc