BigInteger实现最大的整数

  • 存在问题

在java中的基本整数数据类型long类型最大表示范围为:-263 ~ 263-1,若想要使用更大的数值可使用BigInteger来表达。

  • 问题解决
// 若希望表示比long类型范围还大的整数数据,则需要借助java.math.BigInteger类型描述。
BigInteger ba = new BigInteger("1000000");
BigInteger bb = new BigInteger("2000000");

// 实现加法
BigInteger add = ba.add(bb);
System.out.println("add = " + add);

// 实现减法
BigInteger subtract = ba.subtract(bb);
System.out.println("subtract = " + subtract);

// 实现乘法
BigInteger multiply = ba.multiply(bb);
System.out.println("multiply = " + multiply);

// 实现除法
BigInteger divide = bb.divide(ba);
System.out.println("divide = " + divide);

// 实现除法得商与取模得余
BigInteger[] bigIntegers = bb.divideAndRemainder(ba);
String s = Arrays.toString(bigIntegers);
System.out.println("s = " + s);