How to calculate modulo
Divide, round the answer down to a whole number, multiply back, and subtract. What is left is a mod n. Here are your numbers:
Here it is with your numbers:
- Divide: 17 ÷ 5 is 3.4.
- Round down to the whole number below: q is 3.
- Multiply back: 5 × 3 is 15.
- 17 mod 5 = 17 − 15, which is 2
It means 17 is 3 × 5 plus 2; every programming language agrees here.
Modulo is handy for anything that wraps around. 193 cm is 1 m and 93 cm, because 193 mod 100 is 93; minutes past the hour are the total minutes mod 60.
Source OpenStax Introduction to Python Programming · 2.5 Dividing integers: floor division and modulo ↗Python Language Reference · 6.7 Binary arithmetic operations: the % (modulo) operator ↗
Modulo of negative numbers
With a negative number, “round down” matters. −13 ÷ 5 is −2.6; rounding down gives −3, and −13 − 5 × (−3) is 2. That is Python’s rule: the answer has the sign of the divisor. JavaScript, C and Java round toward 0 instead (−2), so their % gives −3, with the sign of the number being divided. When both numbers have the same sign, the two rules agree.
| a mod n | Python | JavaScript, C, Java |
|---|---|---|
| 13 mod 5 | 3 | 3 |
| −13 mod 5 | 2 | −3 |
| 13 mod −5 | −2 | 3 |
| −13 mod −5 | −3 | −3 |
| 7 mod 4 | 3 | 3 |
| 1 mod 3 | 1 | 1 |
| 3.14 mod 0.7 | 0.34 | 0.34 |
Source MDN Web Docs · Remainder (%): JavaScript’s remainder takes the sign of the dividend ↗
FAQs
What does modulo mean?
Modulo means the remainder after division. 7 mod 4 is 3, because 4 goes into 7 once with 3 left over. Programmers write it with %, and read 7 % 4 as “seven mod four”. The number you divide by is called the modulus.
Source OpenStax Introduction to Python Programming · 2.5 Dividing integers: floor division and modulo ↗
How do I calculate 1 mod 3?
3 goes into 1 zero times, so all of the 1 is left over: 1 mod 3 is 1. Whenever the first number is smaller than the second (and both are positive), the answer is the first number: 3 mod 5 is 3 and 2 mod 4 is 2.
What happens if you mod a negative?
It depends on the convention. Python (and this calculator’s main answer) gives the result the sign of the divisor, so −13 mod 5 is 2. JavaScript, C and Java give it the sign of the number being divided, so −13 % 5 is −3. Both are right: they differ by the divisor, 5.
Source MDN Web Docs · Remainder (%): JavaScript’s remainder takes the sign of the dividend ↗
Sources
- OpenStax Introduction to Python Programming: 2.5 Dividing integers: floor division and modulo
- Python Language Reference: 6.7 Binary arithmetic operations: the % (modulo) operator
- MDN Web Docs: Remainder (%): JavaScript’s remainder takes the sign of the dividend