Java Guava | ceilingPowerOfTwo() method of IntMath Class
Last Updated :
23 Jan, 2019
The ceilingPowerOfTwo(int x) method of Guava’s IntMath class accepts a parameter and calculates the smallest power of two greater than the values passed in the parameter. This method is equivalent to checkedPow(2, log2(x, CEILING)).
Syntax :
public static int ceilingPowerOfTwo(int x)
Parameter: This method accepts a single parameter x which is of integer type and returns the smallest power of two greater than the values passed in the parameter.
Return Value : Smallest power of two greater than or equal to x.
Exceptions :
- IllegalArgumentException : This method throws an IllegalArgumentException if x <= 0.
- ArithmeticException: This method throws an ArithmeticException if the next-higher power of two is not representable as an int, i.e. when x > 2^30.
Below examples illustrate the ceilingPowerOfTwo() method of IntMath class:
Example 1 :
import java.math.RoundingMode;
import com.google.common.math.IntMath;
class GFG {
public static void main(String args[])
{
int a1 = 63 ;
if (IntMath.isPrime(a1))
System.out.println(a1 + " is a prime number" );
else
System.out.println(a1 + " is not a prime number" );
int a2 = 17 ;
if (IntMath.isPrime(a2))
System.out.println(a2 + " is a prime number" );
else
System.out.println(a2 + " is not a prime number" );
}
}
|
Output :
Smallest power of 2 greater than or equal to 25 is : 32
Smallest power of 2 greater than or equal to 65 is : 128
Example 2 :
import java.math.RoundingMode;
import com.google.common.math.IntMath;
class GFG {
static int findCeilPow( int x)
{
try {
int ans = IntMath.ceilingPowerOfTwo(x);
return ans;
}
catch (Exception e) {
System.out.println(e);
return - 1 ;
}
}
public static void main(String args[])
{
int n = - 4 ;
try {
findCeilPow(n);;
}
catch (Exception e) {
System.out.println(e);
}
}
}
|
Output :
java.lang.IllegalArgumentException: x (-4) must be > 0
Reference :
https://google.github.io/guava/releases/20.0/api/docs/com/google/common/math/IntMath.html#ceilingPowerOfTwo-int-
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...