ls lib/number-theory/

Number theory for competitive programming

lib / Number theory for competitive programming

The number theory that LeetCode, HackerRank and Codeforces problems keep asking for: gcd, primes and sieves, modular arithmetic, counting mod p, and fast factoring, with proofs short enough to remember and tested Python you can paste.

For anyone who solves LeetCode, HackerRank or Codeforces problems and keeps meeting the same few ideas from number theory: gcd, primes, modular arithmetic, counting mod a prime. Each lesson proves what it uses, in a few lines you can remember, and gives Python you can paste into a solution. The code, with tests that check every function against brute force, is in the companion repository cp-math, tagged per lesson.

It assumes you write Python and know what // and % do on positive numbers. No number theory is assumed. Where C++ behaves differently (integer overflow, the sign of %), the lesson says so.

Divisibility and the Euclidean algorithm

Primes and factorization

Modular arithmetic

Counting mod p

Large numbers