Consider:
long y = 1; for (int i = 49; i > 43; i--) { y*= i; } long x = 49*48*47*46*45*44; // = 1478412928 long y // = 10068347520
Why are the results different although the calculation is even?
Is there an explanation?
Advertisement
Answer
49*48*47*46*45*44
is a multiplication of int
literals, and therefore performs int
multiplications resulting in an int
value. It overflows in this case (since the result is larger than Integer.MAX_VALUE
) before you assign the result to the long
variable. Hence the result is incorrect.
Change it to 49L*48*47*46*45*44
or (long)49*48*47*46*45*44
to perform long
multiplication.
In your first calculation, on the other hand, you begin with a long
variable whose value is 1
, and the loop multiplies that long
with an int
in each iteration, performing long
multiplication, so there’s no overflow.