Keep residues and normalize them
Preserve remainders under addition and multiplication, and treat division separately.
Understand the idea
For m > 0, congruent integers share a remainder class. Addition, subtraction, and multiplication preserve congruence. In C++, normalize a negative remainder using x %= m, then add m if x < 0.
Trace a small example
−3 modulo 7 has canonical residue 4. A huge decimal integer can be processed digit by digit using r = (10r + digit) mod m. For 12345 modulo 7 the final remainder is 4. Modular prefix queries subtract and normalize.
Conditions and cost
Bound intermediate sums and products before evaluating them: taking % after overflow is too late. Ordinary division of residues does not represent modular division. That operation requires an inverse.
What canonical residue represents −3 modulo 7?
Turn the idea into code
Compute the canonical residue of 4 − 9 modulo 6.
Give me a hint
Normalize the remainder of −5.
Show the explained solution
The answer is 1 because −5 + 6 = 1.
Your notes
Mark complete when you can explain it yourself.