Preparing for Java Interview?

My books Grokking the Java Interview and Grokking the Spring Boot Interview can help

Download PDF

How to use BigInteger class in Java? Large Factorial Example

In Java, the BigInteger class, part of the java.math package, provides a powerful and flexible solution for dealing with arbitrarily large integers that exceed the capacity of primitive data types like int or long. This class is particularly useful when precision and magnitude are crucial, such as in cryptographic applications, mathematical computations, or scenarios where large integers are involved. Unlike primitive data types, BigInteger can handle numbers of virtually unlimited size, making it an essential tool for developers facing challenges related to integer overflow or the need for extensive precision. In this guide, we will explore the fundamentals of using the BigInteger class, covering instantiation, basic arithmetic operations, conversion, and the practical scenarios where its usage becomes indispensable. You will also understand the capabilities of BigInteger empowers developers to tackle numerical challenges with confidence in Java applications. For example, we will use BigInteger to calculate factorial of large number.
 
When you calculate factorial of a relatively higher number most of the data type in Java goes out of their limit.  For example, you cannot use int or long variables to store the factorial of a number greater than 50. 

In those scenarios where int and long are not big enough to represent an integral value, you can use java.math.BigInteger class. BigInteger variable can represent an integral number, there is no theoretical limit, but it allocates only enough memory required to hold all the bits of data it is asked to hold. 

There is not any time you need this class but it's good to know about it and that's why I am giving one scenario which is perfectly suitable for using BigInteger class. 

In this article, you will learn how to calculate the factorial of large numbers using the BigInteger object. We will use the same formula, we have used to calculate normal factorials as discussed in my previous post about factorials.



How to use BigInteger class in Java

Here is our sample Java program to calculate large factorials. You will use BigInteger class to hold the result of the calculation. Remember this class is not inside java.lang package, hence you need to explicitly import it, as we have done in this example.  

How to use BigInteger in Java

Another thing to keep in mind is that this class is Immutable and any change on the BigInteger object will result in another object. So, if you forget to store the result back, you will lose it. The original object will always remain in the same state even after addition, subtraction or multiplication.

import java.math.BigInteger;

/**
 * Java Program to calculate factorial of large numbers using 
 * BigInteger class.
 *
 * @author WINDOWS 8
 */
public class BigIntegerDemo {

    public static void main(String args[]) {
        BigInteger result = factorial(BigInteger.valueOf(5));
        System.out.println("factorial of 5 : " + result);

        result = factorial(BigInteger.valueOf(10));
        System.out.println("factorial of 10 : " + result);
        
        result = factorial(BigInteger.valueOf(50));
        System.out.println("factorial of 50 : " + result);
    }

    /**
     * Java method to calculate factorial of large number.
     *
     * @param number BigInteger
     * @return factorial of number as BigInteger
     */
    public static BigInteger factorial(BigInteger number) {

        // factorial of 0 and 1 is always 1 - base case
        if (number == BigInteger.ZERO || number == BigInteger.ONE) {
            return BigInteger.ONE;
        }
        
         // !n = n*!n-1 - recursive call      
        return number.multiply(factorial(number.subtract(BigInteger.ONE)));

    }

}

Output :
factorial of 5 : 120
factorial of 10 : 3628800
factorial of 50 : 3041409320171337804361260816606476884437764156896
0512000000000000


There is no maximum and minimum limit of BigInteger class, in theory, there is no limit for BigInteger. You should use BigInteger whenever you need to represent a big integer number, i.e. something which is not floating-point but cannot be represented using long data type.


Things to Remember :
1. BigInteger class is in java.math package, so you need to specifically import it, it will not be imported automatically like java.lang package.

2. Similar to String, BigInteger class is also immutable, so any modification e.g. addition, multiplication will produce a new instance of BigInteger, leaving the original object intact.

3. Theoretically BigInteger has no limit of numbers.

4. BigInteger class helps to deal with very large numbers in Java.

That's all about how to use BigInteger class in Java to store large numbers. We have seen how to calculate factorial and use the result in the BigInteger object.  In conclusion, the BigInteger class in Java stands as a versatile and indispensable tool for handling large integer values, surpassing the limitations of primitive data types. 

As demonstrated in this tutorial, its flexibility and precision make it well-suited for a variety of applications, ranging from cryptographic algorithms to complex mathematical computations. By leveraging the functionalities provided by BigInteger, developers can ensure accurate and reliable representation of large integer values without concerns of overflow or loss of precision. 

This class proves to be an essential asset in scenarios where numerical accuracy and magnitude matter, and its inclusion in the java.math package enhances Java's capabilities for robust and scalable arithmetic operations.

Understanding how to effectively use the BigInteger class equips developers with the means to address a broader spectrum of numerical challenges in their Java applications.

4 comments:

  1. Thanks for finally talking about >"How to use BigInteger class in Java? Large Factorial Example" <Loved it!

    ReplyDelete
  2. Wow that was unusual. I just wrote an incredibly long
    comment but after I clicked submit my comment didn't show up.
    Grrrr... well I'm not writing all that over again. Anyways, just wanted to say excellent blog!

    ReplyDelete
  3. Way cool! Some very valid points! I appreciate you writing this write-up and also the
    rest of the website is extremely good.

    ReplyDelete
    Replies
    1. Thank you, much appreciated that you like my work.

      Delete

Feel free to comment, ask questions if you have any doubt.