modular arithmetic
Discrete mathematics is the study of mathematics in systems that are countable, such as the set of integers.
Modular arithmetic is a topic of discrete mathematics that is defined as integer arithmetic. This means that there are no decimals. Most operations are very similar to "regular" arithmetic:
- 5 + 3 = 8
- 5 - 3 = 2
- 5 * 3 = 15
It actually gets tricky with division:
- 5 / 3 = 1
5 ÷ 3 actually equals 1.66666, but since there are no decimals, the result is truncated to the integer 1. The remaining .66666 is calculated using a new operator called modulo.
- 5 % 3 = 2
The result of the modulo operation is the remainder of the division. So, in our example:
5 ÷ 3 =
(5 / 3) + (5 % 3) =
1 + 2 / 3 =
1.66666
Note that the result of a modulo operation will always be an integer between 0 and the modulus minus 1. This special property is what makes modular arithmetic very useful in programming.