BigInteger class is used for the mathematical operation which involves very big integer calculations that are outside the limit of all available primitive data types.
For example factorial of 100 contains 158 digits in it so we can’t store it in any primitive data type available. We can store as large Integer as we want in it. There is no theoretical limit on the upper bound of the range because memory is allocated dynamically but practically as memory is limited you can store a number which has Integer.MAX_VALUE number of bits in it which should be sufficient to store mostly all large values.
Syntax:
1) Declaration:
int a, b; BigInteger A, B;
2) Initialization:
a = 54; b = 23; A = BigInteger.valueOf(54); B = BigInteger.valueOf(37);
And for Integers available as string you can initialize them as:
A = new BigInteger(“54”); B = new BigInteger(“123456789123456789”);
3) Mathematical operations:
BigInteger C = A.add(B);
Other similar function are subtract() , multiply(), divide(), remainder()
Extraction of value from BigInteger:
int x = A.intValue(); // value should be in limit of int x long y = A.longValue(); // value should be in limit of long y String z = A.toString();
Task:
Take two numeric strings as input denoting two large integers and print their sum using BigIntegers.
Example Input:
34 20
Example Output:
54