问题
For three n-bit signed integers a, b, and c (such as 32-bit), is it always true that a * (b + c) == (a * b) + (a * c), taking into account integer overflow?
I think this is language-independent, but if it's not, I'm specifically interested in the answer for Java.
回答1:
Yes, it holds, because integer arithmetic is modulo arithmetic over finite rings.
You can see some theoretical discussion here: https://math.stackexchange.com/questions/27336/associativity-commutativity-and-distributivity-of-modulo-arithmetic
回答2:
Yes, this is always true.
It is a property that holds because you are effectively doing arithmetic modulo 2^32. The fact that Java ints are signed complicates things slightly (and means that you can't assume you are doing the equivalent of modulo arithmetic in general), but doesn't affect this particular distributive property.
A thought experiment is to consider implementing it using repeated addition, and consider what happens when it overflows. Since the order of doing additions doesn't affect the result with ints (even with overflows) then neither does doing the multiplications as repeated additions in a different order. And since int multiply is always equivalent to repeated addition, the results must also be the same for re-ordered multiplication. Q.E.D.
回答3:
The distributive property holds for modulo arithmetic; since, fixed bit length two's complement integer arithmetic is homomorphic to modulo arithmetic for the same (unsigned) bit length, the distributive property holds when using two's complement arithmetic.
A more detailed explanation can be found here.
回答4:
Yes, it does hold in Java, including in the overflow case. (Certain other languages don't specify overflow behavior, in which case no guarantees are made.)
回答5:
For 2's complement math on signed integer the question boils down to:
is (a*(b+c))%(2**32) === (a*b+a*c)%(2**32)
so for 2's complement signed integer math it's always true.
For non-2's complement signed integer math I guess it depends on how overflows are handled. If it reflects modulo math then it's true.
来源:https://stackoverflow.com/questions/14189299/are-fixed-width-integers-distributive-over-multiplication