math.ceiling java_Java Guava BigIntegerMath ceilingPowerOfTwo()用法及代码示例

Guava BigIntegerMath类的ceilingPowerOfTwo(BigInteger x)方法返回大于或等于x的2的最小幂。这等效于BigInteger.valueOf(2).pow(log2(x,CEILING))。

用法:

public static BigInteger

ceilingPowerOfTwo(BigInteger x)

参数:此方法将数字x作为其最大幂为2的参数。

返回值:此方法返回给定数字x的2的上限功率。

异常:如果x <= 0,则此方法引发IllegalArgumentException。

以下示例说明了BifIntegerMath.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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值