The rule
a mod b = a − b × ⌊a ÷ b⌋
Why it works
The modulo operation returns what is left after dividing. For positive numbers everyone agrees on the answer; for negatives there are two defensible conventions, and different languages picked different ones.
How to do it by hand
- Divide and keep only the whole part of the quotient
- Multiply that back by the divisor
- Subtract from the dividend
- What is left is the remainder
What is worth knowing
The disagreement over negatives is real and worth knowing: −7 mod 3 is −1 in C, Java and JavaScript, and 2 in Python and Ruby. Both follow consistently from their definition of integer division, and neither is wrong. The mathematical convention is the second, because it keeps the result in the range 0 to b−1, which is what modular arithmetic needs. That property is why the mathematical version is what underlies clock arithmetic, hashing, checksums and every cryptographic algorithm that uses modular exponentiation.