Mathematically they are the same but the computer has a limited number of bits to represent numbers and if you exceed that limit you will get unexpected results.
See the following example:
Imagine the maximum value that could be stored is 200
and you wanted to compute X * Y % 100
.
Lets try some values for X
and Y
:
X = 103 and Y = 98 ==> 3 * 98 > 296 OVERFLOW
X = 103 and Y = 103 ==> 3 * 3 > 9 OK
In case 2, if you take the modulus of both before multiplying, you get a result below 200. But if you only take from one variable, you would have 309 % 200, but 309 would become some twisted value since the type can only represent up to 200.
In case 1, you would have to come up with another strategy (maybe a bigger type or transform your multiplication into sums) because the result of the multiplication would extrapolate the 200 limit.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…