Calculate a mod b which, for positive numbers, is the remainder of a divided by b in a division problem. The modulo operation finds the remainder, so if you were dividing a by b and there was a remainder of n, you would say a mod b = n.
How to Do a Modulo Calculation
The modulo operation finds the remainder of a divided by b. To do this by hand just divide two numbers and note the remainder. If you needed to find 27 mod 6, divide 27 by 6.
- 27 mod 6 = ?
- 27 ÷ 6 = 4 with a remainder of 3
- 27 mod 6 = 3
Example Modulo Calculation
You need to write a piece of software that tells a user whether a number they input is a multiple of 4. You can use the modulo calculation to accomplish this.
If a number is a multiple of 4, when you divide it by 4 the remainder will be 0. So you would create the logic to take an input and use the mod 4 operation on it. If the result is 0 the number is a multiple of 4 otherwise the number is not a multiple of 4.
The logic for this part of your program would be:
- x is the number input by the user
- If x mod 4 = 0 then x is a multiple of 4
- Else x is not a multiple of 4
If you did not use the mod operator you would have to do the math in your code. For example you would have to calculate "is 496 a multiple of 4?". You would divide 496 by 4, so 496 / 4 = 124 with no remainder. In terms of mod, 496 mod 4 = 0, so yes, 496 is a multiple of 4.
Is 226 a multiple of 4? Divide 226 by 4, so 226 / 4 = 56 with a remainder of 2. 226 mod 4 = 2, so no, 226 is not a multiple of 4.
In some calculators and computer programming languages a % b is the same as a mod b is the same as a modulo b where % or mod are used as the modulo operators.
Example: 1 mod 2
1 mod 2 is a situation where the divisor, 2, is larger than the dividend, 1, so the remainder you get is equal to the dividend, 1.
For 1 divided by 2, 2 goes into 1 zero times with a remainder of 1. So 1 mod 2 = 1.
Similarly, 5 mod 10 = 5 since 10 divides into 5 zero times with 5 left over as the remainder.
For positive numbers, whenever the divisor (modulus) is greater than the dividend, the remainder is the same as the dividend.
Explore modular arithmetic and modulo operations further including a mod b for negative numbers.
Kahn Academy, What is Modular Arithmetic?
Better Explained, Fun with Modular Arithmetic
Wikipedia, Applications of Modular Arithmetic
Kahn Academy, Congruence Modulo