Java Guava | pow(int b, int k) method of IntMath Class
The method pow(int b, int k) of Guava’s IntMath class returns b to the kth power. Even if the result overflows, it will be equal to BigInteger.valueOf(b).pow(k).intValue(). This implementation runs in O(log k) time.
Syntax:
public static int pow(int b, int k)
Exception: The method pow(int b, int k) throws IllegalArgumentException if k < 0.
Example 1:
import java.math.RoundingMode;
import com.google.common.math.IntMath;
class GFG {
static int findPow( int b, int k)
{
int ans = IntMath.pow(b, k);
return ans;
}
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);
}
}
|
Output:
4 to the 5th power is: 1024
12 to the 3th power is: 1728
Example 2 :
import java.math.RoundingMode;
import com.google.common.math.IntMath;
class GFG {
static int findPow( int b, int k)
{
try {
int ans = IntMath.pow(b, k);
return ans;
}
catch (Exception e) {
System.out.println(e);
return - 1 ;
}
}
public static void main(String args[])
{
int b = 4 ;
int k = - 5 ;
try {
IntMath.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/IntMath.html#pow-int-int-
Last Updated :
21 Jan, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...