tags:

views:

91

answers:

4

I understand that all math is done as the largest data type required to handle the current values but when you transverse a loop how do you explicitly multiply longs? The following code returns 0, I suspect, because of an overflow.

long result = 0L;
List<Long> temp = (List<Long>) getListOfIntegers();
for (int i = 0; i < temp.size(); i++) {
   result *= temp.get(i).longValue();
}
System.out.println(result);
+9  A: 

Changing the first line into the following will help:

long result = 1L;

As multiplying by 0 will give you 0 :)

Pascal Thivent
+6  A: 

result is zero because it starts out as zero, and multiplying zero by anything results in zero.

WhirlWind
FFFFFUUUUUUUUUU! thanks
Bill Szerdy
You might try floating point; it makes all sorts of weird stuff happen you don't expect ;=)
WhirlWind
+2  A: 

You issue lies in this line:

long result = 0L;

You're multiplying everything by 0, which is always 0. Try:

long result = 1L;
Joshua Rodgers
+3  A: 

The loop returns 0 because you initialized result with 0. 0*x = 0.

phihag