Java – exact sum of long arrays

To get the exact sum of long [], I am using the following code 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 by processing numbers divided into two halves and eventually combining parts and Surprisingly, this approach is also effective:

public static BigInteger fastestSum(long[] a) {
    long low = 0;
    long high = 0;
    for (final long x : a) {
        low += x;
        high += (x >> 32);
    }
    // We kNow that low has the lowest 64 bits of the exact sum.
    // We also kNow that BigInteger.valueOf(high).shiftLeft(32) differs from the exact sum by less than 2**63.
    // So the upper half of high is off by at most one.
    high >>= 32;
    if (low < 0) ++high; // Surprisingly,this is enough to fix it.
    return BigInteger.valueOf(high).shiftLeft(64).add(BigInteger.valueOf(low));
}

I don't believe the fastest sum should work as it is I believe it will work, but more needs to be done in the last step However, it passed all my tests (including large random tests) So I asked: can anyone prove it effective or find counterexamples?

Solution

fastestSum(new long[]{+1,-1})  => -18446744073709551616
fastestSum(new long[]{+1,-1})  => -18446744073709551616
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>