Calculating powers of integers

前端 未结 16 1976
情书的邮戳
情书的邮戳 2020-12-08 06:18

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

16条回答
  •  时光说笑
    2020-12-08 06:24

    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.

提交回复
热议问题