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: 12
和 18
的最大公約數(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