📜  Java中的 BigInteger 类

📅  最后修改于: 2022-05-13 01:54:28.511000             🧑  作者: Mango

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 类的方法

MethodAction Performed
add(BigInteger val)Returns a BigInteger whose value is (this + val).
abs()Returns a BigInteger whose value is the absolute value of this BigInteger.
and(BigInteger val)Returns a BigInteger whose value is (this & val).
andNot(BigInteger val)Returns a BigInteger whose value is (this & ~val).
bitCount()Returns the number of bits in the two’s complement representation of this BigInteger that differ from its sign bit.
bitLength()Returns the number of bits in the minimal two’s-complement representation of this BigInteger, excluding a sign bit.
byteValueExact()Converts this BigInteger to a byte, checking for lost information.
clearBit(int n)Returns a BigInteger whose value is equivalent to this BigInteger with the designated bit cleared.
compareTo(BigInteger val)Compares this BigInteger with the specified BigInteger.
divide(BigInteger val)Returns a BigInteger whose value is (this / val).
divideAndRemainder(BigInteger val)Returns an array of two BigIntegers containing (this / val) followed by (this % val).
doubleValue()Converts this BigInteger to a double.
equals(Object x)Compares this BigInteger with the specified Object for equality.
flipBit(int n)Returns a BigInteger whose value is equivalent to this BigInteger with the designated bit flipped.
floatValue()Converts this BigInteger to a float.
gcd(BigInteger val)Returns a BigInteger whose value is the greatest common divisor of abs(this) and abs(val).
getLowestSetBit()Returns the index of the rightmost (lowest-order) one bit in this BigInteger (the number of zero bits to the right of the rightmost one bit).
hashCode()Returns the hash code for this BigInteger.
 intValue()Converts this BigInteger to an int.
intValueExact()Converts this BigInteger to an int, checking for lost information.
isProbablePrime(int certainty)Returns true if this BigInteger is probably prime, false if it’s definitely composite.
longValue()Converts this BigInteger to a long.
longValueExact()Converts this BigInteger to a long, checking for lost information.
max(BigInteger val)Returns the maximum of this BigInteger and val.
min(BigInteger val)Returns the minimum of this BigInteger and val.
mod(BigInteger mReturns a BigInteger whose value is (this mod m).
modInverse(BigInteger m)Returns a BigInteger whose value is (this-1 mod m).
modPow(BigInteger exponent, BigInteger mReturns a BigInteger whose value is (thisexponent mod m).
multiply(BigInteger val)Returns a BigInteger whose value is (this * val).
negate()Returns a BigInteger whose value is (-this).
nextProbablePrime()Returns the first integer greater than this BigInteger that is probably prime.
not()Returns a BigInteger whose value is (~this).
or(BigInteger val)Returns a BigInteger whose value is (this | val).
pow(int exponent)Returns a BigInteger whose value is (thisexponent).
probablePrime(int bitLength, Random rnd)Returns a positive BigInteger that is probably prime, with the specified bitLength.
remainder(BigInteger val)Returns a BigInteger whose value is (this % val).
setBit(int n)Returns a BigInteger whose value is equivalent to this BigInteger with the designated bit set.
shiftLeft(int n)Returns a BigInteger whose value is (this << n).
shiftRight(int n)Returns a BigInteger whose value is (this >> n).
shortValueExact()Converts this BigInteger to a short, checking for lost information.
signum()Returns the signum function of this BigInteger.
sqrt()Returns the integer square root of this BigInteger.
sqrtAndRemainder()Returns an array of two BigIntegers containing the integer square root s of this and its remainder this – s*s, respectively.
subtract(BigInteger val)Returns a BigInteger whose value is (this – val).
testBit(int n)Returns true if and only if the designated bit is set.
toByteArray()Returns a byte array containing the two’s-complement representation of this BigInteger.
toString()Returns the decimal String representation of this BigInteger.
toString(int radix)Returns the string representation of this BigInteger in the given radix.
valueOf(long val)Returns a BigInteger whose value is equal to that of the specified long.
xor(BigInteger val)Returns a BigInteger whose value is (this ^ val).

插图:

100 的阶乘包含 158 位数字,因此我们无法将其存储为任何可用的原始数据类型。我们可以在其中存储任意大小的 Integer。范围的上限没有理论上的限制,因为内存是动态分配的,但实际上由于内存有限,您可以存储一个具有 Integer.MAX_VALUE 位数的数字,这应该足以存储几乎所有大值。

例子:

Java
// 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

所以在了解了 BigInteger 类的函数之后,我们可以轻松解决许多复杂的问题,但是请记住,由于 BigInteger 类内部使用整数数组进行处理,所以对 BigInteger 对象的操作不如对原语的操作快。 BigIntgers 上的 add函数不会占用与 BigInteger 长度成正比的恒定时间,因此程序的复杂性会相应改变。

必读:

  • Java中的大斐波那契数
  • BigInteger 类还提供素数的快速方法。