Hi,

Another API alternative would be to add a version that triggers a lambda on overflow and allow the caller to determine the value or throw.

public static long multiplyExact(long x,long y,LongBinaryOperator recompute) {
    long r =x *y;
    long ax =Math.abs(x);
    long ay =Math.abs(y);
    if (((ax |ay) >>>31 !=0)) {
// Some bits greater than 2^31 that might cause overflow // Check the result using the divide operator // and check for the special case of Long.MIN_VALUE * -1 if (((y !=0) && (r /y !=x)) ||
           (x ==Long.MIN_VALUE &&y == -1)) {
           return recompute.applyAsLong(x,y);
        }
    }
    return r;
}

$.02, Roger

On 12/13/24 8:22 AM, Raffaello Giulietti wrote:


On 2024-12-12 23:58, Charles Oliver Nutter wrote:

Question two: Am I losing the benefits of *Exact if I use the following code to "pre-check" for overflow?

long high = Math.multiplyHigh(a, b);
if (high == 0) return Math.multiplyExact(a, b);
return bigIntegerMultiply(a, b);


For your specific multiplication use case you might try with

long high = Math.multiplyHigh(a, b);
long low = a * b;
if (high == 0) return low;
return "the big integer consisting of high and low";

It might be possible that the multiplyHigh() and * on the same operands, when appearing adjacent to each other, get optimized to just one instruction.
And if not, they might be executed "in parallel" inside the CPU.


HTH
Raffaello

Reply via email to