synopsis · Thinking tools · chapter 9
Math & Number Theory
9 cards, about a minute. Read them the night before an interview, or right after the chapter to lock it in.
- what it is
Interview number theory is five tools —
gcd, the sieve,% M, fast power, nCr — plus digit peeling with% 10and/ 10. - template
Euclid:
while (b != 0) { int r = a % b; a = b; b = r; } return a;— O(log min(a, b)). - template
Fast power:
if ((e & 1) == 1) r = r * b % m; b = b * b % m; e >>= 1;— O(log e) steps. - use it when
"Modulo 10⁹+7" → reduce after every + and ×,
longfor products, divide by multiplying witha^(p−2). - cost
Sieve up to n: O(n log log n) time, O(n) memory. One number: trial division to √n, O(1) memory.
- trap
(a * b) % Mwith ints overflows before the%. Write(long) a * b % M. - trap
Java's
%keeps the left operand's sign:-7 % 3 == -1. UseMath.floorModor((x % m) + m) % m. - pro tip
Digit loops: guard
rev > MAX / 10beforerev * 10 + d. Test 0, negatives andInteger.MIN_VALUE. - use it when
Weighted random → prefix sums + binary search for the first
prefix[i] ≥ ticket.
Shaky on a card? Open the chapter or flip its recall cards.