Most explanations miss one important step, let's fill the gap using another example.
Given the following:
Dividend: 16
Divisor: 6
The modulus function looks like this:
16 % 6 = 4
Let's determine why this is.
First, perform integer division, which is similar to normal division, except any fractional number (a.k.a. remainder) is discarded:
16 / 6 = 2
Then, multiply the result of the above division (2
) with our divisor (6
):
2 * 6 = 12
Finally, subtract the result of the above multiplication (12
) from our dividend (16
):
16 - 12 = 4
The result of this subtraction, 4
, the remainder, is the same result of our modulus above!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…