What Is the Modulo Operation?
The modulo operation (often abbreviated as "mod") finds the remainder after division of one number by another. Given two numbers, the dividend a and the divisor b, the modulo operation returns the remainder r when a is divided by b. It is expressed as a mod b = r.
The modulo operation is fundamentally related to integer division through the equation: a = q × b + r, where q is the quotient (the integer part of the division) and r is the remainder (the modulo result).
How to Calculate Modulo
To calculate a mod b manually, follow these steps:
- Divide a by b to get the full division result.
- Take the integer part of that division (the quotient q). For positive numbers, this means rounding down (floor). For negative dividends, the behavior depends on the convention used (truncated vs. floored division).
- Multiply the quotient by the divisor: q × b.
- Subtract that product from the original dividend: r = a - q × b. The result is the remainder.
Common Modulo Examples
10 mod 3 = 1
10 divided by 3 is 3 with a remainder of 1.
25 mod 7 = 4
25 divided by 7 is 3 with a remainder of 4.
100 mod 10 = 0
100 is evenly divisible by 10, so the remainder is 0.
7 mod 2 = 1
Used to check if a number is odd: odd numbers have 7 mod 2 = 1.
Practical Applications of Modulo
The modulo operation is widely used in programming, mathematics, and everyday computations:
- Checking Even/Odd: A number is even if n mod 2 = 0, and odd if n mod 2 = 1.
- Clock Arithmetic: Hours wrap around using mod 12 or mod 24. For example, 15:00 in 12-hour format is 15 mod 12 = 3 PM.
- Cyclic Patterns: Repeating patterns in arrays, circular buffers, and round-robin scheduling all use modulo.
- Cryptography: Modular arithmetic is the foundation of RSA encryption and other cryptographic algorithms.
- Hash Functions: Hash tables use modulo to map keys to bucket indices.
- Day of Week: Calendar calculations use mod 7 to determine the day of the week.
Modulo in Programming Languages
Most programming languages provide a modulo operator, though the symbol and behavior with negative numbers can vary:
- JavaScript, C, C++, Java: Use the
%operator (truncated division). - Python: Uses the
%operator (floored division, always returns non-negative result when divisor is positive). - Haskell: Provides both
mod(floored) andrem(truncated).
Important Properties of Modulo
- The result of a mod b is always in the range 0 to |b| - 1 (for the floored definition).
- If a mod b = 0, then b divides a evenly (b is a factor of a).
- Modulo is distributive over addition: (a + b) mod n = ((a mod n) + (b mod n)) mod n.
- Modulo is distributive over multiplication: (a × b) mod n = ((a mod n) × (b mod n)) mod n.