Math Operations on BigInteger in Java

Java 8Object Oriented ProgrammingProgramming

Let us apply the following operations on BigInteger using the in-built methods in Java.

Addition: add() method
Subtraction: subtract() method
Multiplication: multiply() method
Division: divide() method

Let us create three BigInteger objects.

BigInteger one = new BigInteger("98765432123456789");
BigInteger two = new BigInteger("94353687526754387");
BigInteger three = new BigInteger("96489687526737667");

Apply mathematical operations on them.

one = one.add(two);
System.out.println("Addition Operation = " + one);
one = one.multiply(two);
System.out.println("Multiplication Operation = " + one);

The following is an example −

Example

 Live Demo

import java.math.BigInteger;
public class Main {
   public static void main(String[] args) {
      BigInteger one = new BigInteger("98765432123456789");
      BigInteger two = new BigInteger("94353687526754387");
      BigInteger three = new BigInteger("96489687526737667");
      one = one.add(two);
      System.out.println("Addition Operation = " + one);
      one = one.multiply(two);
      System.out.println("Multiplication Operation = " + one);
      two = three.subtract(two);
      System.out.println("Subtract Operation = " + two);
      two = three.divide(two);
      System.out.println("Division Operation = " + two);
   }
}

Output

Addition Operation = 193119119650211176
Multiplication Operation = 18221501070917918273532554434429112
Subtract Operation = 2135999999983280
Division Operation = 45
raja
Published on 20-Dec-2018 15:15:25
Advertisements