How it’s calculated
Dividing a by n gives a whole-number quotient q and a remainder r so that a = n × q + r. The modulo operation (a mod n) is that remainder. For positive numbers there is only one sensible answer: 17 ÷ 5 = 3 remainder 2, so 17 mod 5 = 2.
Why negative numbers differ. The two conventions round the quotient differently. Truncating rounds toward zero; flooring rounds toward minus infinity. For −17 ÷ 5 = −3.4 the truncated quotient is −3, leaving remainder −17 − 5 × (−3) = −2. The floored quotient is −4, leaving −17 − 5 × (−4) = 3. Mathematicians and clock arithmetic use the floored result, which always lands in 0 to n − 1 for a positive n. Programming languages disagree, so check which one yours uses.
Whole numbers are handled exactly with big-integer arithmetic, so huge values (hundreds of digits) are fine, and decimals are handled exactly as decimals, with no rounding error: 7.5 mod 2 = 1.5.
Frequently asked questions
What is −17 mod 5?
With the floored (mathematical) definition it is 3, because −17 = 5 × (−4) + 3. With the truncated definition used by the % operator in C, Java and JavaScript, the remainder is −2.
When is the answer 0?
The remainder is 0 exactly when n divides a evenly. Any whole number mod 1 is 0.
Can the divisor be negative?
Yes. The floored remainder then takes the sign of the divisor (zero or negative), while the truncated remainder still takes the sign of a. Most everyday uses have a positive divisor.
Why is mod 0 an error?
Because division by zero is undefined, so there is no quotient or remainder.
Embed this calculator
Add this free calculator to your own website. Copy the code below into your page’s HTML:
Need this calculator branded, changed or built around your own prices?See custom business solutions →
Sources
- MDN Web Docs: Remainder (%) operator (truncated remainder, sign of the dividend) — Mozilla
- Python documentation: Expressions, binary arithmetic operations (floor division and % with the sign of the divisor) — Python Software Foundation
Formulas are taken from the free public references above. Results are provided “as is” for informational and educational purposes only. See our disclaimer.
Added · Last updated · How we check our calculators
Spotted a mistake or missing option? Report a problem· Suggest a calculator