BigInteger

定义

BigInteger是Java中的一个类,用于表示任意大小的整数。它可以处理比long类型更大的整数,因为BigInteger没有任何大小限制。

BigInteger类提供了各种方法,使用户能够执行各种整数操作,如加法、减法、乘法、除法、取余等。它还提供了方法来比较两个BigInteger对象的大小,并执行位运算。

常用方法

下面是一些常用的BigInteger方法:

  1. add(BigInteger other):将当前BigInteger对象与另一个BigInteger对象相加,并返回结果。
  2. subtract(BigInteger other):从当前BigInteger对象中减去另一个BigInteger对象,并返回结果。
  3. multiply(BigInteger other):将当前BigInteger对象与另一个BigInteger对象相乘,并返回结果。
  4. divide(BigInteger other):将当前BigInteger对象除以另一个BigInteger对象,并返回结果。
  5. mod(BigInteger other):将当前BigInteger对象对另一个BigInteger对象取余,并返回结果。
  6. compareTo(BigInteger other):比较当前BigInteger对象与另一个BigInteger对象的大小。如果当前对象小于另一个对象,则返回负数;如果当前对象大于另一个对象,则返回正数;如果两个对象相等,则返回0。
  7. pow(int exponent):将当前BigInteger对象的值提升到指定的幂次方,并返回结果。
  8. negate():返回当前BigInteger对象的相反数。
  9. 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类可以处理非常大的整数,并执行各种数学运算操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值