Ernest,
Yep. We discuss this one in detail in Puzzle 3 ("Long Division"). Note that a better fix is:
By making the
first factor in the sequence of multiplications a long, we don't have to worry about where the overflow occurs: the entire computation is done using longs.
Regards,
Josh and Neal
Originally posted by Ernest Friedman-Hill:
Because the constants on the right-hand-sides of these assignments are integers, not longs, the multiplication is done with integers, and the final int result is then converted to a long. "a" is less than the maximum value of an int by about a factor of 25, but "b" is way over, so "b" overflows and you end up with an unexpected value -- i.e., you get (int) (24*60*60*1000*1000L), which, just by happenstance, is about 5 times as large as "a", rather than 1000 times.
If you change the declaration of "b" to be
public static final long b =24*60*60*1000*1000L;
(note that "L" on the end) then the multiplies are done using longs, and you'll get the answer you expect.