Guava LongMath類的方法pow(long b,int k)將b返回到第k次冪。即使結果溢出,也將等於BigInteger.valueOf(b).pow(k).longValue()。此實現在O(log k)時間中運行。
用法:
public static long pow(long b, int k)
參數:該方法接受兩個參數b和k。參數b稱為基數,它升為k-th的冪。
返回值:此方法返回b的k-th冪。
異常:如果k為負,則此方法引發IllegalArgumentException。
範例1:
// Java code to show implementation of
// pow(long b, int k) method of Guava's
// LongMath Class
import java.math.RoundingMode;
import com.google.common.math.LongMath;
class GFG {
// Driver code
public static void main(String args[])
{
long b1 = 4;
int k1 = 5;
long ans1 = LongMath.pow(b1, k1);
System.out.println(b1 + " to the " + k1
+ "th power is:"
+ ans1);
long b2 = 12;
int k2 = 3;
long ans2 = LongMath.pow(b2, k2);
System.out.println(b2 + " to the " + k2
+ "rd power is:"
+ ans2);
}
}
輸出:
4 to the 5th power is:1024 12 to the 3rd power is:1728
範例2:
// Java code to show implementation of
// pow(long b, int k) method of Guava's
// LongMath class
import java.math.RoundingMode;
import com.google.common.math.LongMath;
class GFG {
static long findPow(long b, int k)
{
try {
// Using pow(long b, int k)
// method of Guava's LongMath class
// This should throw "IllegalArgumentException"
// as k < 0
long ans = LongMath.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[])
{
long b = 4;
int k = -5;
try {
// Using pow(long b, int k)
// method of Guava's LongMath class
// This should throw "IllegalArgumentException"
// as k < 0
LongMath.pow(b, k);
}
catch (Exception e) {
System.out.println(e);
}
}
}
輸出:
java.lang.IllegalArgumentException:exponent (-5) must be >= 0
相關用法
- Java Guava LongMath binomial(int n, int k)用法及代碼示例
- Java Guava LongMath isPowerOfTwo(long x)用法及代碼示例
- Java Guava LongMath sqrt(long x, RoundingMode mode)用法及代碼示例
- Java Guava LongMath gcd(long a, long b)用法及代碼示例
- Java Guava LongMath mean(long x, long y)用法及代碼示例
- Java Guava LongMath mod(long x, long m)用法及代碼示例
- Java LongMath.checkedMultiply(int a, int b)用法及代碼示例
- Java LongMath.checkedPow(long b, int k)用法及代碼示例
- Java LongMath log10(long x, RoundingMode mode)用法及代碼示例
- Java LongMath.divide(long, long, RoundingMode)用法及代碼示例
- Java LongMath.checkedAdd(long a, long b)用法及代碼示例
注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 Java Guava | pow(long b, int k) of LongMath Class with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。