Java BigIntegerMath ceilingPowerOfTwo() 函数
Guava的BigIntegerMath类的 ceilingPowerOfTwo(BigInteger x) 方法返回大于或等于x的 最小 二 阶幂 。这相当于BigInteger.valueOf(2).pow(log2(x, CEILING) )。
语法
public static BigInteger
ceilingPowerOfTwo(BigInteger x)
参数。该方法以数字x为参数,要找到其上限为2的幂。
返回值。该方法返回给定数字x的2的最大功率。
异常: 如果x<=0,该方法会产生 IllegalArgumentException 。
下面的例子说明了BigIntegerMath. ceilingPowerOfTwo()方法。
例1 :
// Java code to show implementation of
// ceilingPowerOfTwo(BigInteger x) method
// of Guava's BigIntegerMath class
import java.math.*;
import com.google.common.math.BigIntegerMath;
class GFG {
// Driver code
public static void main(String args[])
{
BigInteger n1 = BigInteger.valueOf(25);
// Using ceilingPowerOfTwo(BigInteger x) method of
// Guava's BigIntegerMath class
BigInteger ans = BigIntegerMath.ceilingPowerOfTwo(n1);
System.out.println("Smallest power of 2 greater "
+ "than or equal to "
+ n1 + " is: " + ans);
BigInteger n2 = BigInteger.valueOf(65);
// Using ceilingPowerOfTwo(BigInteger x) method of
// Guava's BigIntegerMath class
BigInteger ans1 = BigIntegerMath.ceilingPowerOfTwo(n2);
System.out.println("Smallest power of 2 greater "
+ "than or equal to "
+ n2 + " is: " + ans1);
}
}
输出。
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(BigInteger x) method
// of Guava's BigIntegerMath class
import java.math.*;
import com.google.common.math.BigIntegerMath;
class GFG {
// Driver code
public static void main(String args[])
{
try {
BigInteger n = BigInteger.valueOf(0);
// Using ceilingPowerOfTwo(BigInteger x) method of
// Guava's BigIntegerMath class
// This should raise "IllegalArgumentException"
// as n is <= 0
BigInteger ans = BigIntegerMath.ceilingPowerOfTwo(n);
System.out.println("Smallest power of 2 greater "
+ "than or equal to n is : " + ans);
}
catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
输出。
Exception: java.lang.IllegalArgumentException: x (0) must be > 0
参考资料: https://google.github.io/guava/releases/21.0/api/docs/com/google/common/math/BigIntegerMath.html#ceilingPowerOfTwo-java.math.BigInteger-