The method pow(long b, int k) of Guava’s LongMath Class returns b to the kth power. Even if the result overflows, it will be equal to BigInteger.valueOf(b).pow(k).longValue(). This implementation runs in O(log k) time.
Syntax:
public static long pow(long b, int k)
Parameters: The method accepts two parameters, b and k. The parameter b is called base which is raised to the k-th power.
Return Value: This method returns the k-th power of b.
Exception: This method throws IllegalArgumentException if k is negative.
Example 1:
import java.math.RoundingMode;
import com.google.common.math.LongMath;
class GFG {
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);
}
}
|
Output:
4 to the 5th power is: 1024
12 to the 3rd power is: 1728
Example 2:
import java.math.RoundingMode;
import com.google.common.math.LongMath;
class GFG {
static long findPow( long b, int k)
{
try {
long ans = LongMath.pow(b, k);
return ans;
}
catch (Exception e) {
System.out.println(e);
return - 1 ;
}
}
public static void main(String args[])
{
long b = 4 ;
int k = - 5 ;
try {
LongMath.pow(b, k);
}
catch (Exception e) {
System.out.println(e);
}
}
}
|
Output:
java.lang.IllegalArgumentException: exponent (-5) must be >= 0
Reference: https://google.github.io/guava/releases/20.0/api/docs/com/google/common/math/LongMath.html#pow-long-int-