5.3 An intuitive understanding of the modulo operation
Once again, the operands are called dividend and divisor (hinting at how similar rem
and mod
are):
modulus = dividend mod divisor
Consider the following example:
x mod 3
This operation maps x
into the range:
[0,3) = {0,1,2}
That is, zero is included (opening square bracket), 3 is excluded (closing parenthesis).
How does mod
perform this mapping? It is easy if x
is already inside the range:
> 0 mod 3
0
> 2 mod 3
2
If x
is greater than or equal to the upper boundary of the range, then the upper boundary is subtracted from x
until it fits into the range:
> 4 mod 3
1
> 7 mod 3
1
That means we are getting the following mapping for non-negative integers:
x: 0 1 2 3 4 5 6 7
x mod 3: 0 1 2 0 1 2 0 1
This mapping is extended as follows, so that it includes negative integers:
x: -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7
x mod 3: 2 0 1 2 0 1 2 0 1 2 0 1 2 0 1
Note how the range [0,3) is repeated over and over again.