定义
BigInteger是Java中的一个类,用于表示任意大小的整数。它可以处理比long类型更大的整数,因为BigInteger没有任何大小限制。
BigInteger类提供了各种方法,使用户能够执行各种整数操作,如加法、减法、乘法、除法、取余等。它还提供了方法来比较两个BigInteger对象的大小,并执行位运算。
常用方法
下面是一些常用的BigInteger方法:
- add(BigInteger other):将当前BigInteger对象与另一个BigInteger对象相加,并返回结果。
- subtract(BigInteger other):从当前BigInteger对象中减去另一个BigInteger对象,并返回结果。
- multiply(BigInteger other):将当前BigInteger对象与另一个BigInteger对象相乘,并返回结果。
- divide(BigInteger other):将当前BigInteger对象除以另一个BigInteger对象,并返回结果。
- mod(BigInteger other):将当前BigInteger对象对另一个BigInteger对象取余,并返回结果。
- compareTo(BigInteger other):比较当前BigInteger对象与另一个BigInteger对象的大小。如果当前对象小于另一个对象,则返回负数;如果当前对象大于另一个对象,则返回正数;如果两个对象相等,则返回0。
- pow(int exponent):将当前BigInteger对象的值提升到指定的幂次方,并返回结果。
- negate():返回当前BigInteger对象的相反数。
- abs():返回当前BigInteger对象的绝对值。
除了以上的方法之外,BigInteger还可以通过valueOf()方法来创建一个BigInteger对象,也可以通过toString()方法将BigInteger对象转换为字符串表示形式。
示例
下面是一个使用BigInteger的示例:
import java.math.BigInteger;
public class BigIntegerExample {
public static void main(String[] args) {
BigInteger num1 = new BigInteger("12345678901234567890");
BigInteger num2 = new BigInteger("98765432109876543210");
BigInteger sum = num1.add(num2);
System.out.println("Sum: " + sum);
BigInteger difference = num1.subtract(num2);
System.out.println("Difference: " + difference);
BigInteger product = num1.multiply(num2);
System.out.println("Product: " + product);
BigInteger quotient = num1.divide(num2);
System.out.println("Quotient: " + quotient);
BigInteger remainder = num1.mod(num2);
System.out.println("Remainder: " + remainder);
}
}
以上代码会输出以下结果:
Sum: 111111111011111111100
Difference: -86419753208641975320
Product: 121932631137021795882785350734296100
Quotient: 0
Remainder: 12345678901234567890
从示例中可以看出,BigInteger类可以处理非常大的整数,并执行各种数学运算操作。