What is the Modulo Operation?
The modulo operation (often written as "mod" or "%") finds the remainder when one integer is divided by another. For example, 17 mod 5 = 2, because 17 divided by 5 is 3 with a remainder of 2. The mathematical definition is: a mod b = a - b * floor(a / b).
Uses and Applications of Modulo
Clock Arithmetic
Hours wrap around every 12 (or 24). If it is 10 o'clock and you add 5 hours, it becomes 3 o'clock: (10 + 5) mod 12 = 3.
Even/Odd Check
A number is even if n mod 2 = 0, and odd if n mod 2 = 1. This is the most basic use of modulo in programming.
Day of the Week
Days cycle every 7. Given a starting day, you can find the day after N days: (startDay + N) mod 7.
Cyclic Indexing
In programming, modulo is used to cycle through arrays or create circular buffers. Index wraps back to 0 when it reaches the array length.
Hashing
Hash functions use modulo to map data to a fixed range of buckets: hash(key) mod tableSize.
Cryptography
Modular arithmetic is the foundation of RSA encryption and many other cryptographic algorithms.
Properties of Modulo
- a mod b always yields a value between 0 and b - 1 (for positive b).
- (a + b) mod n = ((a mod n) + (b mod n)) mod n -- addition property.
- (a * b) mod n = ((a mod n) * (b mod n)) mod n -- multiplication property.
- a mod 1 = 0 for any integer a.
- a mod a = 0 for any nonzero integer a.
Negative Numbers
The behavior of modulo with negative numbers varies by programming language. In mathematics, the result always has the same sign as the divisor. For example, -7 mod 3 = 2 (not -1). This calculator follows the mathematical convention.
Modulo in Programming
Most programming languages use the % operator for modulo: Python, JavaScript, C, Java, and more. Python's % operator follows the mathematical convention (result has the sign of the divisor), while C and Java may return a negative remainder.