How Modulo of Negative Numbers Works
The modulo (or remainder) operation finds what is left over after dividing one number by another. When both numbers are positive, every programming language and math textbook agrees on the answer. Once a negative dividend or divisor is involved, though, there are three different conventions in common use — truncated, floored, and Euclidean — and they can give different results for the same inputs. This calculator shows all three side by side, along with the quotient used to get the floored result.
The three conventions, explained
Truncated remainder (used by JavaScript's %, C, C++, and Java): the quotient a/b is rounded toward zero (truncated), then r = a − b·trunc(a/b). The remainder always takes the same sign as the dividend a. For example, −7 % 3 = −1, because trunc(−7/3) = trunc(−2.333) = −2, so −7 − 3×(−2) = −1.
Floored modulo (used by Python's % and standard mathematical "mod" notation): the quotient is rounded down (floor), then m = a − b·floor(a/b). The result always takes the same sign as the divisor b. For the same example, floor(−7/3) = floor(−2.333) = −3, so m = −7 − 3×(−3) = 2 — a positive result, because the divisor 3 is positive.
Euclidean modulo: the remainder is always forced to be non-negative, using r = a − |b|·floor(a/|b|), so 0 ≤ r < |b| no matter the sign of a or b. This is the convention used in Euclidean division and is handy whenever a negative result would be invalid, such as array indices or wrapped angles.
Common sources of error
- Assuming one universal answer: −7 mod 3 is −1, 2, or 2 depending on convention — always state which one you mean when sharing a result.
- Copying a language's operator without checking its convention: JavaScript, C, and Java use truncated remainder; Python, Ruby, and most math textbooks use floored modulo.
- Dividing by zero: the modulo operation is undefined when the divisor is 0 — this calculator flags that case instead of returning a misleading number.
Checking your result
A quick sanity check: the floored and Euclidean results should always be non-negative when the divisor is positive, since 0 ≤ result < |b|. The truncated result can be negative whenever the dividend is negative. If your divisor is positive and your truncated remainder is negative, add the divisor to it to get the floored (and, in this case, Euclidean) result — that shortcut works whenever the signs of a and b differ.