ArithmeticUtils { public static int mulAndCheck(int x, int y) throws MathArithmeticException { long m = ((long)x) * ((long)y); if (m < Integer.MIN_VALUE || m > Integer.MAX_VALUE) { throw new MathArithmeticException(); } return (int)m; } private  ArithmeticUtils(); static int addAndCheck(int x, int y); static long addAndCheck(long a, long b); @Deprecated static long binomialCoefficient(final int n, final int k); @Deprecated static double binomialCoefficientDouble(final int n, final int k); @Deprecated static double binomialCoefficientLog(final int n, final int k); @Deprecated static long factorial(final int n); @Deprecated static double factorialDouble(final int n); @Deprecated static double factorialLog(final int n); static int gcd(int p, int q); static long gcd(final long p, final long q); static int lcm(int a, int b); static long lcm(long a, long b); static int mulAndCheck(int x, int y); static long mulAndCheck(long a, long b); static int subAndCheck(int x, int y); static long subAndCheck(long a, long b); static int pow(final int k,
                          final int e); @Deprecated static int pow(final int k, long e); static long pow(final long k,
                           final int e); @Deprecated static long pow(final long k, long e); static BigInteger pow(final BigInteger k, int e); static BigInteger pow(final BigInteger k, long e); static BigInteger pow(final BigInteger k, BigInteger e); @Deprecated static long stirlingS2(final int n, final int k); static boolean isPowerOfTwo(long n);  }
@Test public void testMulAndCheck() { int big = Integer.MAX_VALUE; int bigNeg = Integer.MIN_VALUE; Assert.assertEquals(big, ArithmeticUtils.mulAndCheck(big, 1)); try { ArithmeticUtils.mulAndCheck(big, 2); Assert.fail("Expecting MathArithmeticException"); } catch (MathArithmeticException ex) { } try { ArithmeticUtils.mulAndCheck(bigNeg, 2); Assert.fail("Expecting MathArithmeticException"); } catch (MathArithmeticException ex) { } }
@Test public void testMulAndCheckLong() { long max = Long.MAX_VALUE; long min = Long.MIN_VALUE; Assert.assertEquals(max, ArithmeticUtils.mulAndCheck(max, 1L)); Assert.assertEquals(min, ArithmeticUtils.mulAndCheck(min, 1L)); Assert.assertEquals(0L, ArithmeticUtils.mulAndCheck(max, 0L)); Assert.assertEquals(0L, ArithmeticUtils.mulAndCheck(min, 0L)); Assert.assertEquals(max, ArithmeticUtils.mulAndCheck(1L, max)); Assert.assertEquals(min, ArithmeticUtils.mulAndCheck(1L, min)); Assert.assertEquals(0L, ArithmeticUtils.mulAndCheck(0L, max)); Assert.assertEquals(0L, ArithmeticUtils.mulAndCheck(0L, min)); Assert.assertEquals(1L, ArithmeticUtils.mulAndCheck(-1L, -1L)); Assert.assertEquals(min, ArithmeticUtils.mulAndCheck(min / 2, 2)); testMulAndCheckLongFailure(max, 2L); testMulAndCheckLongFailure(2L, max); testMulAndCheckLongFailure(min, 2L); testMulAndCheckLongFailure(2L, min); testMulAndCheckLongFailure(min, -1L); testMulAndCheckLongFailure(-1L, min); }