Guava的IntMath類的ceilingPowerOfTwo(int x)方法接受一個參數,並計算出比該參數中傳遞的值大2的最小冪。此方法等效於checkedPow(2,log2(x,CEILING))。
用法:
public static int ceilingPowerOfTwo(int x)
參數:此方法接受單個參數x,該參數為整數類型,並返回比參數中傳遞的值大2的最小冪。
返回值:大於或等於x的2的最小冪。
異常:
IllegalArgumentException:如果x <= 0,則此方法引發IllegalArgumentException。
ArithmeticException:如果next-higher的2的冪不能表示為int,即x> 2^30時,此方法將引發ArithmeticException。
下麵的示例說明IntMath類的ceilingPowerOfTwo()方法:
範例1:
// Java code to show implementation of
// isPrime(int n) method of Guava's
// IntMath class
import java.math.RoundingMode;
import com.google.common.math.IntMath;
class GFG {
// Driver code
public static void main(String args[])
{
int a1 = 63;
// Using isPrime(int n)
// method of Guava's IntMath class
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;
// Using isPrime(int n)
// method of Guava's IntMath class
if(IntMath.isPrime(a2))
System.out.println(a2 + " is a prime number");
else
System.out.println(a2 + " is not a prime number");
}
}
輸出:
Smallest power of 2 greater than or equal to 25 is:32
Smallest power of 2 greater than or equal to 65 is:128
範例2:
// Java code to show implementation of
// ceilingPowerOfTwo(int x) method of Guava's
// IntMath class
import java.math.RoundingMode;
import com.google.common.math.IntMath;
class GFG {
static int findCeilPow(int x)
{
try {
// Using ceilingPowerOfTwo(int x)
// method of Guava's IntMath class
// This should throw "IllegalArgumentException"
// as x <= 0
int ans = IntMath.ceilingPowerOfTwo(x);
// Return the answer
return ans;
}
catch (Exception e) {
System.out.println(e);
return -1;
}
}
// Driver code
public static void main(String args[])
{
int n = -4;
try {
// Function calling
findCeilPow(n);;
}
catch (Exception e) {
System.out.println(e);
}
}
}
輸出:
java.lang.IllegalArgumentException:x (-4) must be > 0