How it works
The modulo operation gives the remainder after dividing a by n. 17 mod 5 = 2 because 17 = 5 × 3 + 2. It is the basis of "clock arithmetic": 10 hours after 9 o'clock is (9 + 10) mod 12 = 7 o'clock.
For negative numbers, conventions differ. Mathematicians (and Python, Excel and Google Sheets) use floored division, so −7 mod 3 = 2. JavaScript, C and Java use truncated division, where −7 % 3 = −1. The main result here is always non-negative.
Formula
a mod n = a − n × ⌊a ÷ n⌋
Questions people ask
What is −7 mod 3?
In mathematics it is 2, because −7 = 3 × (−3) + 2. In JavaScript or C, −7 % 3 returns −1, because those languages truncate the quotient toward zero.
How do I tell if a number is even with modulo?
A number is even exactly when n mod 2 = 0. More generally, a is divisible by n when a mod n = 0.
Can modulo be used with decimals?
Yes. 7.5 mod 2 = 1.5, because 7.5 = 2 × 3 + 1.5. The formula a − n⌊a/n⌋ works for any real numbers.