Java BigInteger 常用方法与实例


发布日期 : 2024-07-04 04:33:37 UTC

访问量: 10 次浏览

Java BigInteger类

BigInteger类用于涉及非常大的整数计算的数学操作,这些计算超出了所有可用的原始数据类型的限制。

这样一来,BigInteger类的使用就非常方便了,因为它拥有庞大的方法库,而且在竞争性编程中也被大量使用。

下面给出了原始算术中的简单语句及其在BigInteger对象方面的类似语句的列表。

例子

int a, b;                
BigInteger A, B;

初始化过程如下:

a = 54;
b = 23;
A  = BigInteger.valueOf(54);
B  = BigInteger.valueOf(37);

对于可作为字符串的整数,你可以按以下方式初始化它们。

A  = new BigInteger(“54”);
B  = new BigInteger(“123456789123456789”);

为了便于初始化,在BigInteger类中也定义了一些常量,如下所示。

A = BigInteger.ONE;
// Other than this, available constant are BigInteger.ZERO 
// and BigInteger.TEN

数学运算如下。

int c = a + b;
BigInteger C = A.add(B);

其他类似的函数有减法()、乘法()、除法()、余数(),但所有这些函数都以BigInteger为参数,所以如果我们要对整数或字符串进行这种操作,在将它们传递给函数之前,先将它们转换成BigInteger,如下图所示。

String str = “123456789”;
BigInteger C = A.add(new BigInteger(str));
int val  = 123456789;
BigInteger C = A.add(BigInteger.valueOf(val));

从BigInteger中提取数值的方法如下。

int x   =  A.intValue();   // value should be in limit of int x
long y   = A.longValue();  // value should be in limit of long y
String z = A.toString();

比较

if (a < b) {}         // For primitive int
if (A.compareTo(B) < 0)  {} // For BigInteger

实际上compareTo根据数值返回-1(小于),0(相等),1(大于)。对于平等,我们也可以使用。

if (A.equals(B)) {}  // A is equal to B

BigInteger类的方法

方法描述
add(BigInteger val)返回一个BigInteger,其值为(this + val)。
abs()返回一个大Integer,其值是这个大Integer的绝对值。
and(BigInteger val)返回值为(this & val)的大Integer。
andNot(BigInteger val )返回值为(this & ~val)的大Integer。
bitCount()返回这个大整数的二补表示中与符号位不同的位数。
bitLength()返回这个大整数的最小二补表示中的位数,不包括符号位。
byteValueExact()将这个大整数转换为一个字节,并检查是否有丢失的信息。
clearBit(int n)返回一个大整数,其值相当于这个大整数的指定位被清除。
compareTo(BigInteger val)将这个大整数与指定的大整数进行比较。
divide(BigInteger val)返回一个大整数,其值为(this / val)。
divideAndRemainder(BigInteger val)返回一个包含(this / val)和(this % val)的两个大Integer数组。
doubleValue()将这个大整数转换为双数。
equals(Object x)将这个大整数与指定的对象进行比较,看是否相等。
flipBit(int n)返回一个大整数,该大整数的值等同于翻转了指定位的大整数。
floatValue()将这个大整数转换为浮点数。
gcd(BigInteger val)返回一个大整数,其值是abs(this)和abs(val)的最大公除数。
getLowestSetBit()返回这个大整数中最右边(最低阶)一位的索引(最右边一位右侧的零位数)。
hashCode()返回此BigInteger的哈希代码。
intValue()将此BigInteger转换为一个int。
intValueExact()将这个大整数转换为一个int,并检查是否有丢失的信息。
isProbablePrime(int certainty)如果这个大整数可能是质数,则返回true,如果肯定是复合数,则返回false。
longValue()将这个大整数转换为长数。
longValueExact()将这个大整数转换为长数,并检查是否有丢失的信息。
max(BigInteger val)返回这个BigInteger和val的最大值。
min(BigInteger val )返回此BigInteger和val的最小值。
mod(BigInteger m返回一个大整数,其值为(this mod m)。
modInverse(BigInteger m)返回值为(this-1 mod m)的大Integer。
modPow(BigInteger exponent, BigInteger m返回一个大整数,其值为(thisexponent mod m)。
multiply(BigInteger val)返回一个大整数,其值为(this * val)。
negate()返回一个大整数,其值为(-this)。
nextProbablePrime()返回第一个比这个大Integer大的可能是素数的整数。
not()返回值为(~)的大Integer。
or(BigInteger val)返回值为(this
pow(int exponent)返回值为(thisexponent)的大Integer。
probablePrime(int bitLength, Random rnd)返回一个可能是质数的正数大Integer,并指定比特长度。
remainder(BigInteger val)返回一个大整数,其值为(this % val)。
setBit(int n)返回一个大整数,其值等同于这个大整数的指定位。
shiftLeft(int n)返回一个大Integer,其值为(this << n)。
shiftRight(int n)返回一个大整数,其值为(this >> n)。
shortValueExact()将这个大整数转换为短数,并检查是否有丢失的信息。
signum()返回这个大Integer的符号函数。
sqrt()返回这个大整数的平方根。
sqrtAndRemainder()返回两个大整数的数组,分别包含这个大整数的平方根s和它的余数 this-s*s
subtract(BigInteger val)返回一个大整数,其值为(this – val)。
testBit(int n)当且仅当指定的位被设置时返回真。
toByteArray()返回一个包含这个大整数的二进制表示的字节数组。
toString()返回这个大整数的十进制字符串表示。
toString(int radix)返回这个大整数在给定radix中的字符串表示。
valueOf(long val)返回一个大Integer,其值等于指定的long。
xor(BigInteger val)返回一个大整数,其值为(this ^ val)。

举例说明

100的阶乘包含158位数字,所以我们不能把它存储在任何可用的原始数据类型中。我们可以在其中存储尽可能大的整数。因为内存是动态分配的,所以理论上对范围的上限没有限制,但实际上由于内存是有限的,你可以存储一个有Integer.MAX_VALUE位数的数字,这应该足以存储大部分的大值。

例子

// Java program to find large factorials using BigInteger
import java.math.BigInteger;
import java.util.Scanner;
 
public class Example
{
    // Returns Factorial of N
    static BigInteger factorial(int N)
    {
        // Initialize result
        BigInteger f = new BigInteger("1"); // Or BigInteger.ONE
 
        // Multiply f with 2, 3, ...N
        for (int i = 2; i <= N; i++)
            f = f.multiply(BigInteger.valueOf(i));
 
        return f;
    }
 
    // Driver method
    public static void main(String args[]) throws Exception
    {
        int N = 20;
        System.out.println(factorial(N));
    }
}

输出

2432902008176640000

提示:
如果我们要用C++写上述程序,那就太庞大和复杂了,我们可以看看《大数的阶乘》。

因此,在了解了上述 BigInteger 类的功能后,我们可以轻松地解决许多复杂的问题,但请记住,由于 BigInteger 类内部使用整数数组进行处理,对 BigIntegers 对象的操作并不像对基元的操作那样快,BigIntgers上的加法函数所花费的时间不是恒定的,而是与 BigInteger 的长度成比例的,因此程序的复杂性会相应改变。