Java番石榴 | IntMath 类的 pow(int b, int k) 方法
Guava 的 IntMath 类的方法pow(int b, int k)返回b 的 k 次方。即使结果溢出,它也会等于 BigInteger.valueOf(b).pow(k).intValue()。此实现在O(log k)时间内运行。
句法:
public static int pow(int b, int k)
异常:如果 k < 0,方法 pow(int b, int k) 将抛出IllegalArgumentException 。
示例 1:
// Java code to show implementation of
// pow(int b, int k) method of Guava's
// IntMath class
import java.math.RoundingMode;
import com.google.common.math.IntMath;
class GFG {
static int findPow(int b, int k)
{
// Using pow(int b, int k)
// method of Guava's IntMath class
int ans = IntMath.pow(b, k);
// Return the answer
return ans;
}
// Driver code
public static void main(String args[])
{
int b = 4;
int k = 5;
int ans = findPow(b, k);
System.out.println(b + " to the " + k
+ "th power is: "
+ ans);
b = 12;
k = 3;
ans = findPow(b, k);
System.out.println(b + " to the " + k
+ "th power is: "
+ ans);
}
}
输出:
4 to the 5th power is: 1024
12 to the 3th power is: 1728
示例 2:
// Java code to show implementation of
// pow(int b, int k) method of Guava's
// IntMath class
import java.math.RoundingMode;
import com.google.common.math.IntMath;
class GFG {
static int findPow(int b, int k)
{
try {
// Using pow(int b, int k)
// method of Guava's IntMath class
// This should throw "IllegalArgumentException"
// as k < 0
int ans = IntMath.pow(b, k);
// Return the answer
return ans;
}
catch (Exception e) {
System.out.println(e);
return -1;
}
}
// Driver code
public static void main(String args[])
{
int b = 4;
int k = -5;
try {
// Using pow(int b, int k)
// method of Guava's IntMath class
// This should throw "IllegalArgumentException"
// as k < 0
IntMath.pow(b, k);
}
catch (Exception e) {
System.out.println(e);
}
}
}
输出:
java.lang.IllegalArgumentException: exponent (-5) must be >= 0
参考: https://google.github.io/guava/releases/20.0/api/docs/com/google/common/math/IntMath.html#pow-int-int-