BigInteger 数学运算实例

BigInteger 位于不可变对象中,因此你需要将任何数学运算的结果分配给新的 BigInteger 实例。

增加: 10 + 10 = 20

BigInteger value1 = new BigInteger("10");
BigInteger value2 = new BigInteger("10");

BigInteger sum = value1.add(value2);
System.out.println(sum);

输出:20

减产: 10 - 9 = 1

BigInteger value1 = new BigInteger("10");
BigInteger value2 = new BigInteger("9");

BigInteger sub = value1.subtract(value2);
System.out.println(sub);

输出:1

分部: 10/5 = 2

BigInteger value1 = new BigInteger("10");
BigInteger value2 = new BigInteger("5");

BigInteger div = value1.divide(value2);
System.out.println(div);

输出:2

分部: 17/4 = 4

BigInteger value1 = new BigInteger("17");
BigInteger value2 = new BigInteger("4");

BigInteger div = value1.divide(value2);
System.out.println(div);

输出:4

乘法: 10 * 5 = 50

BigInteger value1 = new BigInteger("10");
BigInteger value2 = new BigInteger("5");

BigInteger mul = value1.multiply(value2);
System.out.println(mul);

输出:50

功率: 10 ^ 3 = 1000

BigInteger value1 = new BigInteger("10");
BigInteger power = value1.pow(3);
System.out.println(power);

输出:1000

余数: 10%6 = 4

BigInteger value1 = new BigInteger("10");
BigInteger value2 = new BigInteger("6");

BigInteger power = value1.remainder(value2);
System.out.println(power);

输出:4

GCD: 1218 的最大公约数(GCD)是 6

BigInteger value1 = new BigInteger("12");
BigInteger value2 = new BigInteger("18");

System.out.println(value1.gcd(value2));

输出:6

最多两个 BigIntegers:

BigInteger value1 = new BigInteger("10");
BigInteger value2 = new BigInteger("11");

System.out.println(value1.max(value2));

输出:11

至少两个 BigIntegers:

BigInteger value1 = new BigInteger("10");
BigInteger value2 = new BigInteger("11");

System.out.println(value1.min(value2));

输出:10