Here you can find the source of powExact(long x, int y)
Parameter | Description |
---|---|
x | base |
y | power |
Parameter | Description |
---|---|
ArithmeticException | if the result overflows a long<br>or if x = 0 and y < 0 (resulting in infinity) |
public static long powExact(long x, int y) throws ArithmeticException
//package com.java2s; //License from project: Open Source License public class Main { /**/* w w w . j a v a2 s. c o m*/ * Returns value of x raised in power y, throwing an exception if the result overflows a long. * @param x base * @param y power * @return x<sup>y</sup> * @throws ArithmeticException if the result overflows a long<br> * or if x = 0 and y < 0 (resulting in infinity) */ public static long powExact(long x, int y) throws ArithmeticException { if (y >= 0) { long z = 1L; while (true) { if ((y & 1) != 0) z = Math.multiplyExact(z, x); y >>>= 1; if (y == 0) break; x = Math.multiplyExact(x, x); } return z; } else { if (x == 0L) throw new ArithmeticException("Negative power of zero is infinity"); if (x == 1L) return 1L; if (x == -1L) return (y & 1) == 0 ? 1L : -1L; return 0L; } } /** * Returns value of x raised in power y, throwing an exception if the result overflows an int. * @param x base * @param y power * @return x<sup>y</sup> * @throws ArithmeticException if the result overflows an int<br> * or if x = 0 and y < 0 (resulting in infinity) */ public static int powExact(int x, int y) throws ArithmeticException { if (y >= 0) { int z = 1; while (true) { if ((y & 1) != 0) z = Math.multiplyExact(z, x); y >>>= 1; if (y == 0) break; x = Math.multiplyExact(x, x); } return z; } else { if (x == 0) throw new ArithmeticException("Negative power of zero is infinity"); if (x == 1) return 1; if (x == -1) return (y & 1) == 0 ? 1 : -1; return 0; } } }