Wednesday, September 2, 2015

How to use BigInteger class in Java

Some time we need to store some really big numbers. Though we are already using the primitive data types int and long. But sometime we need to store values which cannot be held by these data type.

We will understand the problem with the help of factorial calculation as follows:

If we are calculating factorial of 13 or more and will try to store it in int datatype then we will not get the correct result, and this will result in overflow.
Again if we are calculating factorial of 21 or more it cannot be held through long data type. It will give the same error as mentioned above.

To hold the factorial of 21 or more we need BigInteger class of java.math package. As name suggests BigInteger class is used to hold the really big number, something which is even bigger than maximum value of long primitive

e.g. 2^63 -1 or 9223372036854775807L. The java.math.BigInteger class provides all the operation similar to Java’s integer primitive and have all the relevant methods from Java.Math.

To declare a BigInteger we use:

BigInteger number = BigInteger.valueOf(long number);
Also worth noting that, similar to java.lang.String and other wrapper classes BigInteger is also Immutable in Java, which means its important to store result back into same variable, otherwise result of calculation will be lost. BigInteger stores numbers as 2's complement number like int primitive and support operation supported by int variables and all relevant methods from java.lang.Math class. Additionally it also provide support for modular arithmetic, bit manipulation, primality testing, prime generation, GCD calculation and other miscellaneous operations.

Important things about BigInteger class in Java
BigInteger class in Java is designed to deal with really large numbers in Java, but to do that it’s very important that you make yourself familiar with class. Here are some key points about java.math.BigInteger class :

1. The BigInteger class is used to represent arbitrarily large numbers. Overflow doesn't occur as is the case with int and long primitive.

2. The BigInteger class is immutable which means that the object on which the multiply function was invoked doesn't change the integer it is holding. The multiplication is performed and a new BigInteger is returned which needs to be stored in the variable fact.

3. BigInteger provides operations similar to int primitive type in Java, additionally it provide support for prime generation, bit manipulation, GCD calculations etc.

4. You can create BigInteger object by giving number as String or byte array using constructor, or you can convert a long value to BigInteger using valueOf() method as shown below :

BigInteger bigIntegerFromLong = BigInteger.valueOf(292909333L);
BigInteger bigIntegerFromString = new BigInteger("338948938948");
Java Program to Calculate Factorial of Large Number

Here is our sample Java program to calculate factorial for large numbers, well given number is not exactly large but the factorial value is definitely large. For example, factorial of 45 is 119622220865480194561963161495657715064383733760000000000, which is clearly out of bound for even a long data type. Since theoretically BigInteger has no limit it can hold these values as shown in following example.
There are many ways to calculate factorial like using recursion, dynamic programming or iteration. In following example we have used iteration to calculate factorial in Java.


import java.math.BigInteger;

/**
 * Write a Java program to calculate factorial of large numbers using
 * BigInteger.
 *
 * @author RD
 *
 */
public class LargeFactorialDemo {

    public static void main(String args[]) {

        System.out.printf("Factorial of 32 is %s %n", factorial(32));
        System.out.printf("Factorial of 0 is %s %n", factorial(0));
        System.out.printf("Factorial of 1 is %s %n", factorial(1));
        System.out.printf("Factorial of 5 is %s %n", factorial(5));
        System.out.printf("Factorial of 41 is %s %n", factorial(41));
        System.out.printf("Factorial of 45 is %s %n", factorial(45));

    }

    /*
     * Java method to calculate factorial of a large number
     * @return BigInteger factorial of given number
     */
    public static BigInteger factorial(int number) {
        BigInteger factorial = BigInteger.ONE;

        for (int i = number; i > 0; i--) {
            factorial = factorial.multiply(BigInteger.valueOf(i));
        }

        return factorial;
    }

}

Output
Factorial of 32 is 263130836933693530167218012160000000
Factorial of 0 is 1
Factorial of 1 is 1
Factorial of 5 is 120
Factorial of 41 is 33452526613163807108170062053440751665152000000000
Factorial of 45 is 119622220865480194561963161495657715064383733760000000000

You can see that how large factorial of 45 is, clearly its not possible to use long data type to store such huge integral values. You need to use BigInteger class to store such big values.


Hope you liked the post. Please consider leaving a comment and follow the blog.

No comments:

Post a Comment

Java garbage collection

In this post , we ’ ll take a look at how garbage collection works , why it ’ s important in Java , and how it works in...