To get the exact sum of a long[] , I use the following snippet.
public static BigInteger sum(long[] a) { long low = 0; long high = 0; for (final long x : a) { low += (x & 0xFFFF_FFFFL); high += (x >> 32); } return BigInteger.valueOf(high).shiftLeft(32).add(BigInteger.valueOf(low)); }
It works great by processing numbers divided into two halves, and finally combines partial amounts. Surprisingly, this method also works:
public static BigInteger fastestSum(long[] a) { long low = 0; long high = 0; for (final long x : a) { low += x; high += (x >> 32); }
I do not think fastestSum should work as is. I believe that it can work, but something else needs to be done at the last stage. However, it passes all my tests (including large random tests). So I ask: can anyone prove that it works or find a counterexample?
java sum integer-arithmetic
maaartinus
source share