Java中如何使用BigInteger进行大数计算

BigInteger类用于处理超出long范围的整数,通过字符串或valueOf方法创建对象,支持加减乘除、取模、幂运算和比较等操作,所有运算返回新实例,适用于高精度计算场景。

Java中处理超出long范围的整数时,BigInteger类是标准解决方案。它支持任意精度的整数运算,适用于大数加减乘除、幂运算、取模、比较等操作。下面介绍常用方法和使用方式。

创建BigInteger对象

BigInteger不能直接用基本类型赋值,必须通过字符串或字节数组构造。

  • BigInteger a = new BigInteger("12345678901234567890"); // 用字符串创建
  • BigInteger b = BigInteger.valueOf(100); // 小数值可用valueOf快速创建

基本算术运算

BigInteger是不可变对象,所有操作都返回新实例。

  • BigInteger sum = a.add(b); // 加法
  • BigInteger diff = a.subtract(b); // 减法
  • BigInteger mul = a.multiply(b); // 乘法
  • BigInteger di

    v = a.divide(b); // 除法(整除)
  • BigInteger rem = a.remainder(b); // 取余
  • BigInteger mod = a.mod(b); // 模运算(结果非负)

其他常用操作

除了四则运算,BigInteger还提供多种实用方法。

  • BigInteger pow = a.pow(3); // a的3次方,指数为int
  • int cmp = a.compareTo(b); // 比较:1(a>b), 0(相等), -1(a
  • boolean eq = a.equals(b); // 判断是否相等
  • BigInteger abs = a.abs(); // 绝对值
  • BigInteger neg = a.negate(); // 取负
  • int bitLength = a.bitLength(); // 二进制位数
  • boolean isZero = a.equals(BigInteger.ZERO); // 判断是否为0

系统预定义了常用值:BigInteger.ZERO、BigInteger.ONE、BigInteger.TEN,推荐直接使用。

实际示例

计算两个大数的乘积并判断大小:

BigInteger x = new BigInteger("99999999999999999999");
BigInteger y = new BigInteger("88888888888888888888");
BigInteger product = x.multiply(y);
int result = x.compareTo(y);
System.out.println("乘积: " + product);
System.out.println("x > y ? " + (result > 0));

基本上就这些。只要注意对象不可变和构造方式,BigInteger用起来很直观。