How the Modulo Operator Works
The modulo operation finds the remainder left over after dividing one number by another. Given a dividend a and a non-zero divisor n, "a mod n" is the value r such that a = n x q + r for some integer quotient q. The catch is that mathematicians, and different programming languages, do not always agree on how to choose q and r when a or n is negative — that disagreement is exactly what this calculator makes visible by computing all three common conventions side by side.
Formula and method
All three conventions start from the same division a/n but round the quotient differently, which changes the sign of the remainder:
- Truncated (C, Java, JavaScript's
%): q = trunc(a/n) (round toward zero), so r = a - n x trunc(a/n). The remainder has the same sign as the dividend a. - Floored (Python's
%, Ruby): q = floor(a/n) (round toward negative infinity), so r = a - n x floor(a/n). The remainder has the same sign as the divisor n. - Euclidean: q is chosen so the remainder is always r ≥ 0, using r = a - |n| x floor(a/|n|). This is the convention used in number theory and always satisfies 0 ≤ r < |n|.
For positive a and positive n, all three formulas give the identical result. They only diverge when a or n is negative — for example, -7 mod 3 is -1 (truncated), 2 (floored), and 2 (Euclidean).
Common sources of error
- Assuming one convention everywhere: JavaScript, C, and Java's
%operator is truncated, while Python's and Ruby's%is floored — porting code between languages without adjusting for negative operands silently changes results. - Dividing by zero: a mod 0 is undefined; the calculator flags this instead of returning a meaningless value.
- Forgetting non-integer inputs work too: the same floor/trunc formulas apply to decimal numbers, not just whole numbers — 7.5 mod 2 = 1.5 under the floored convention.
Checking your result
For the floored and Euclidean conventions with n > 0, the remainder must always satisfy 0 ≤ r < n — if your result falls outside that range, recheck the formula. A quick sanity check for any convention: (a - r) / n should equal an integer quotient with no remainder left over.
Applications
Modulo arithmetic shows up constantly in everyday computing and math:
- Clock and calendar arithmetic: converting 25 hours to "1 hour past midnight" uses 25 mod 24; wrapping the 12-hour clock uses mod 12.
- Cyclic array indexing: repeating patterns or wrapping around a fixed-size list uses
index mod lengthso indices never run off the end. - Parity and divisibility checks: a number is even exactly when n mod 2 = 0, and more generally n mod k = 0 tests divisibility by k.
- Checksums and hashing: credit-card Luhn validation, ISBN check digits, and hash-table bucket assignment all rely on modulo to fold large numbers into a fixed range.