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
相關用法
- Java Guava IntMath gcd(int a, int b)用法及代碼示例
- Java Guava IntMath mean()用法及代碼示例
- Java Guava IntMath mod()用法及代碼示例
- Java Guava IntMath ceilingPowerOfTwo()用法及代碼示例
- Java Guava IntMath isPrime()用法及代碼示例
- Java Guava IntMath isPowerOfTwo()用法及代碼示例
- Java Guava IntMath floorPowerOfTwo()用法及代碼示例
- Java Guava IntMath binomial()用法及代碼示例
- Java Guava IntMath sqrt(int x, RoundingMode mode)用法及代碼示例
- Java IntMath.checkedSubtract(int a, int b)用法及代碼示例
- Java IntMath.checkedPow(int b, int k)用法及代碼示例
- Java IntMath.checkedAdd(int a, int b)用法及代碼示例
- Java IntMath.checkedMultiply(int a, int b)用法及代碼示例
注:本文由純淨天空篩選整理自bansal_rtk_大神的英文原創作品 Java Guava | pow(int b, int k) method of IntMath Class。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。