How to calculate a mod n
- Enter the number a and the modulus n.
- Read a mod n and the equation a = q × n + r that it comes from.
- With negative numbers, compare the conventions different languages use.
Examples
| Expression | Result | Because |
|---|---|---|
| 17 mod 5 | 2 | 17 = 3 × 5 + 2 |
| 20 mod 4 | 0 | 4 divides 20 |
| 3 mod 7 | 3 | 3 = 0 × 7 + 3 |
| −7 mod 3 | 2 (floored) | −7 = −3 × 3 + 2 |
Even or odd
n mod 2 is 0 for even numbers and 1 for odd ones, which is the quickest test in most programming languages.
Modular arithmetic
In arithmetic mod n, numbers wrap around after n − 1, like hours on a clock. Sums and products can be reduced at any step: (17 × 23) mod 5 = (2 × 3) mod 5 = 1. That trick keeps huge calculations small, which is what makes modern encryption practical.