Modulo Calculator

Find a mod n (the remainder) for whole numbers of any size or decimals, with quotient and remainder under both the truncated and floored conventions.

A whole number of any size, or a decimal like 7.5. Use a point for decimals and no thousands separators.
Cannot be 0.

Results

−17 mod 5 (floored, never negative for n > 0)
3
Differs from the truncated remainder because a and n have opposite signs.
Quotient (floored, rounded down)
−4
Remainder (truncated, like C / JavaScript %)
−2
Quotient (truncated, rounded toward 0)
−3
Check
a = n × quotient + remainder (−17 = 5 × −4 + 3)

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.

a = n × q + r truncated: q = trunc(a ÷ n), r has the sign of a (C, Java, JavaScript %) floored: q = floor(a ÷ n), r has the sign of n (Python %, mathematical mod)

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

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