01Arithmetic on a clock
a mod m is the remainder after dividing by m, a value in 0..m−1. Think of a clock: 15 o'clock is 3 on a 12-hour face. The useful fact is that you can reduce at any moment during addition, subtraction and multiplication:
(a + b) mod m = ((a mod m) + (b mod m)) mod m(a · b) mod m = ((a mod m) · (b mod m)) mod m
So a long product never needs to be big: reduce after every step. Two warnings. Subtraction can go negative in C++ and Java (-3 % 10 == -3), so write ((a - b) % m + m) % m. And division does not work this way. Instead you multiply by an inverse, which we get from fast power below.