The modulo operation returns what is left after dividing as many whole times as possible. 17 mod 5 is 2, because 5 goes into 17 three times with 2 to spare. For positive numbers this is uncontroversial and matches the remainder from primary school long division.
Negative numbers split the world in two. Under the truncated convention, used by C, Java and JavaScript, the remainder takes the sign of the dividend, so −17 mod 5 is −2. Under the floored convention, used by Python and by mathematicians, the remainder takes the sign of the divisor, so −17 mod 5 is 3. Both are internally consistent and neither is wrong, but mixing them is a reliable source of off-by-one bugs in anything that wraps around, such as clock arithmetic or circular buffers. This page shows both.
The formula
a- The dividend, the number being divided
n- The modulus or divisor
⌊ ⌋- The floor function, rounding down towards minus infinity
quotient- How many whole times n fits into a
How to use this calculator
- Enter the dividend.
- Enter the modulus you are dividing by.
- The gauge shows the floored remainder, which is always non-negative for a positive modulus.
- Compare it with the truncated result below if you are matching a particular language.
Worked examples
17 mod 5
5 fits into 17 three times, leaving 2. Both conventions agree here because the numbers are positive: 17 − 5 × 3 = 2.
Where −17 mod 5 splits
Python returns 3 because it floors the quotient to -4. JavaScript returns -2 because it truncates towards zero. The two differ by exactly the modulus, 5, which is the general rule whenever the signs disagree.
How to read your score
Frequently asked questions
Why do languages disagree about negative modulo?
They round the quotient differently. Truncation rounds towards zero; flooring rounds towards minus infinity. Each then defines the remainder to make the division identity hold, and the two answers differ by one modulus.
Which convention should I use for wrapping an index?
The floored one, since it always returns a value between zero and the modulus. In JavaScript write ((a % n) + n) % n to force that behaviour.
What is modulo used for beyond remainders?
Clock arithmetic, hashing values into buckets, cycling through an array, checksum digits and the whole of public-key cryptography, which is modular arithmetic on very large numbers.
What happens if the modulus is zero?
The operation is undefined, because it implies dividing by zero. This page reports that rather than returning a value.
Modulo under both conventions
| a | n | Floored (Python) | Truncated (JavaScript) | Agree? |
|---|---|---|---|---|
| 17 | 5 | 2 | 2 | yes |
| 20 | 5 | 0 | 0 | yes |
| -17 | 5 | 3 | -2 | no |
| -20 | 5 | 0 | 0 | yes |
| 17 | -5 | -3 | 2 | no |
| -17 | -5 | -2 | -2 | yes |
| 7 | 3 | 1 | 1 | yes |
The two conventions only differ when the dividend and divisor have opposite signs.