Big integer in java(part1)

               Numbers are always unique. If your number’s range is beyond the primitive datatypes like int and long, what will you do?

Java brings you a concept “Big integer”. It holds a very large number. The built in package which supports this concept is

java.math.bigInteger

How to implement big integer in java?

              Here is the sum of two numbers program.

Steps:

  • ·       Include the java.math.BigInteger in your program.
  • ·       Define a class with main() function.
  • ·       Create two objects for BigInteger class and get the input.
  • ·       Add the two big integers and store it in total
  • ·       Display the sum using a print statement.

Program:

import java.math.BigInteger;

class bigIntEg

{

 public static void main(String args[])

 {

  BigInteger bInt1 = new BigInteger("13245687901235637101");  

  BigInteger bInt2 = new BigInteger("98712345678912345210");

  BigInteger total = bInt1.add(bInt2);

  System.out.println("Sum of two big integers are: " +total);

 }

}

Output:

C:\raji\blog>javac bigIntEg.java

C:\raji\blog>java bigIntEg

Sum of two big integers are: 111958033580147982311

Next, basic arithmetic operations are implemented in java.

#Java Program to display the basic arithmetic operations on Big Integers:

              This program uses the four built functions subtract(), multiply(), divide(), remainder() for performing arithmetic operations.

Program:

import java.math.BigInteger;

class bigIntEg

{

 public static void main(String args[])

 {

  BigInteger bInt1 = new BigInteger("98712345678912345210");  

  BigInteger bInt2 = new BigInteger("13245687901235637101");

  BigInteger subtract = bInt1.subtract(bInt2);

  BigInteger mul = bInt1.multiply(bInt2);

  BigInteger div = bInt1.divide(bInt2);

  BigInteger rem = bInt1.remainder(bInt2);

  System.out.println("Subtration of two big integers are: " +subtract);

  System.out.println("Multiplication of two big integers are: " +mul);

  System.out.println("Division of two big integers are: " +div);

  System.out.println("Remainder of two big integers are: " +rem);

 }

}

Just compile and execute the program in the command prompt. You will get the below output.

C:\raji\blog>javac bigIntEg.java

C:\raji\blog>java bigIntEg

Subtration of two big integers are: 85466657777676708109

Multiplication of two big integers are: 1307512922861759172756321086068395636210

Division of two big integers are: 7

Remainder of two big integers are: 5992530370262885503

This is the way of using Big Integers in java. Keep Coding!!!

No comments:

Post a Comment