Glossary Math & Statistics

Modulo

Modulo gives the remainder after division: a mod n is what is left when a is divided by n.

Last reviewed:

AdSense Placeholder
Slot: header_reference_page

In more detail

17 mod 5 = 2, because 17 = 3 × 5 + 2. Modular arithmetic "wraps around" like a clock: on a 12-hour dial 15 mod 12 = 3. Sums and products can be reduced at any step, (a × b) mod n = ((a mod n) × (b mod n)) mod n, which keeps numbers small; that is how computers raise huge numbers to huge powers in cryptography. Most programming languages write it as %.

Why it matters

Modulo appears in calendars, clocks, check digits on barcodes and bank numbers, hash tables (hash mod buckets), round-robin scheduling and testing for even numbers (n % 2 == 0). For negative numbers, languages disagree: −7 mod 3 is 2 in Python (the result takes the sign of the divisor) but −1 in JavaScript and C (the sign of the dividend), so code that wraps an index backwards can produce a negative position.

Example

>>> 17 % 5, 15 % 12, 100 % 7
(2, 3, 2)
>>> -7 % 3          # Python
2
> -7 % 3            // JavaScript
-1

100 days after a Monday is a Wednesday, because 100 mod 7 = 2. 100 hours after 09:00 is 13:00 four days later, because 109 = 4 × 24 + 13. In JavaScript, ((x % n) + n) % n gives the always-positive result.

AdSense Placeholder
Slot: footer_leaderboard