このようなメソッドをJava8のMathパッケージに含める計画がありますが、現在の状況はわかりません。いくつかのソースコードはここから入手できます。実装がどのようにテストされているかはわかりませんが、それでアイデアが得られる可能性があります。
たとえば、int乗算は、longを使用して実行されます。
public static int multiplyExact(int x, int y) {
long r = (long)x * (long)y;
if ((int)r != r) {
throw new ArithmeticException("long overflow");
}
return (int)r;
}
ただし、長い乗算では、より複雑なアルゴリズムが使用されます。
public static long multiplyExact(long x, long y) {
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)) {
throw new ArithmeticException("long overflow");
}
}
return r;
}