Java BigIntegerMath floorPowerOfTwo() 函数

Java BigIntegerMath floorPowerOfTwo() 函数

Guava的BigIntegerMath类的 floorPowerOfTwo(BigInteger x )方法返回小于或等于x的最大2次方。这相当于BigInteger.valueOf(2).pow(log2(x, FLOOR))。

语法:

public static BigInteger floorPowerOfTwo(BigInteger x)

参数: 该方法以大整数 x 为参数,要找出其二的底限幂。

返回值: 该方法返回小于或等于x的最大二的幂。

异常: 如果 x <=0 **,该方法会抛出 **IllegalArgumentException

以下例子说明了BigIntegerMath.floorPowerOfTwo()方法:

例1:

// Java code to show implementation of
// floorPowerOfTwo() 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(10);
 
        // Using floorPowerOfTwo(BigInteger x) method
        // of Guava's BigIntegerMath class
        BigInteger
            ans1
            = BigIntegerMath.floorPowerOfTwo(n1);
 
        System.out.println("Largest power of 2 less "
                           + "than or equal to " + n1
                           + " is: " + ans1);
 
        BigInteger n2 = BigInteger.valueOf(127);
 
        // Using floorPowerOfTwo(BigInteger x) method
        // of Guava's BigIntegerMath class
        BigInteger
            ans2
            = BigIntegerMath.floorPowerOfTwo(n2);
 
        System.out.println("Largest power of 2 less "
                           + "than or equal to " + n2
                           + " is: " + ans2);
    }
}

输出:

Largest power of 2 less than or equal to 10 is: 8
Largest power of 2 less than or equal to 127 is: 64

例2: 要显示IllegalArgumentException

// Java code to show implementation of
// floorPowerOfTwo(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 n1 = BigInteger.valueOf(-3);
 
            // Using floorPowerOfTwo(BigInteger x) method
            // of Guava's BigIntegerMath class
            // This should raise "IllegalArgumentException"
            // as x <= 0
            BigInteger
                ans1
                = BigIntegerMath.floorPowerOfTwo(n1);
 
            System.out.println("Largest power of 2 less "
                               + "than or equal to " + n1
                               + " is: " + ans1);
        }
        catch (Exception e) {
            System.out.println("Exception: " + e);
        }
    }
}

输出:

Exception: java.lang.IllegalArgumentException: x (-3) must be > 0

参考资料: https://google.github.io/guava/releases/21.0/api/docs/com/google/common/math/BigIntegerMath.html#floorPowerOfTwo-java.math.BigInteger-

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程