Is there any other way in Java to calculate a power of an integer?
I use Math.pow(a, b)
now, but it returns a double
, and that is usually a
Guava's math libraries offer two methods that are useful when calculating exact integer powers:
pow(int b, int k) calculates b to the kth the power, and wraps on overflow
checkedPow(int b, int k) is identical except that it throws ArithmeticException
on overflow
Personally checkedPow()
meets most of my needs for integer exponentiation and is cleaner and safter than using the double versions and rounding, etc. In almost all the places I want a power function, overflow is an error (or impossible, but I want to be told if the impossible ever becomes possible).
If you want get a long
result, you can just use the corresponding LongMath methods and pass int
arguments.