Java Language BigInteger BigInteger Mathematical Operations Examples


Example

BigInteger is in an immutable object, so you need to assign the results of any mathematical operation, to a new BigInteger instance.

Addition: 10 + 10 = 20

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

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

output: 20

Substraction: 10 - 9 = 1

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

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

output: 1

Division: 10 / 5 = 2

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

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

output: 2

Division: 17/4 = 4

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

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

output: 4

Multiplication: 10 * 5 = 50

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

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

output: 50

Power: 10 ^ 3 = 1000

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

output: 1000

Remainder: 10 % 6 = 4

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

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

output: 4

GCD: Greatest Common Divisor (GCD) for 12and 18 is 6.

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

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

Output: 6

Maximum of two BigIntegers:

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

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

Output: 11

Minimum of two BigIntegers:

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

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

Output: 10