Modulo Calculator
Calculate a modulo, with the mathematical and programming conventions shown separately because they disagree on negatives.
Everything you type here is processed on your own device. No input is sent to a server, logged, or stored.
What the Modulo Calculator does
The modulo calculator on this page will calculate a modulo, with the mathematical and programming conventions shown separately because they disagree on negatives. Fill in all 3 fields and the result updates as you type — there is no Calculate button to press and no page reload. It is most often used for debugging a negative-number modulo bug in code. We run a second free tools site as well — FreeToolsWorld.org.
How to use it
- Enter the dividend and the modulus.
- Compare the two remainder conventions, which differ for negative inputs.
- Enter an exponent for modular exponentiation.
How it works
Mathematics and most programming languages disagree about negative numbers, and the disagreement causes real bugs. In mathematics, −17 mod 5 is 3, because the result always takes the sign of the modulus. In C, Java, JavaScript and many others, −17 % 5 is −2, because the operator takes the sign of the dividend. Python and Ruby follow the mathematical convention; most C-derived languages do not.
The usual fix in a C-family language is ((a % n) + n) % n, which forces the result into the non-negative range. It is worth writing as a helper rather than inline, because the bug it prevents is the kind that only appears when a value happens to go negative.
Modular exponentiation is computed here by repeated squaring rather than by calculating the power first, because aᵏ overflows long before the modulo would reduce it. That same technique is what makes RSA and Diffie-Hellman practical.
When to use it
- Debugging a negative-number modulo bug in code.
- Wrapping an index around an array length.
- Working out a day of the week or a clock arithmetic problem.
- Computing a modular inverse for a number theory exercise.
Common mistakes to avoid
- Assuming the % operator gives the mathematical modulo for negative values.
- Using a modulus of zero, which is undefined.
- Computing a power before taking the modulo, which overflows.
Frequently asked questions
What is −17 mod 5?
3 under the mathematical convention, where the result takes the sign of the modulus. In C, Java and JavaScript, −17 % 5 gives −2.
How do I get a non-negative modulo in JavaScript?
Use ((a % n) + n) % n. The built-in operator keeps the sign of the dividend, which is rarely what you want for wrapping an index.
What is a modular inverse?
The number x such that a × x ≡ 1 (mod n). It exists only when a and n are coprime, and it is central to RSA key generation.