Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to use the BigInteger class to calculate factorials in Java

Vinisha Maheshwari

In this shot, we will discuss how to use BigInteger class to calculate factorials in Java. For mathematical calculations of very large integer values, we use the BigInteger class present in java.math package. There is no limit on the range of integer values for BigInteger.

Suppose, we want the value, 122!, which is too large to get stored in the primitive data types like int, long. BigInteger gives us the edge to perform calculations with very large integers.

Let’s look at an example.


The factorial of 100 is:


Solution approach

We will be using the BigInteger class which has the .multiply() method and .valueof() method that we will use in our code.

  • The BigInteger.multiply() method multiplies this BigInteger with the passed BigInteger.
  • The BigInteger.valueof() method gives a BigInteger whose value is equal to the value of long passed as parameter.


Let’s look at the code snippet.

  • Enter an input to run the code above.
  • The input value must be big, such as 100.
import java.util.*;
import java.math.BigInteger;
class Main
      public static void main(String[] args) 
            Scanner sc=new Scanner(;
            int n = sc.nextInt();
            System.out.print(n + "! = "+factorial(n));

      public static BigInteger factorial(int n) 
            BigInteger f = new BigInteger("1");
            for (int i = n; i > 0; i--)
                  f = f.multiply(BigInteger.valueOf(i));
            return f;

Enter the input below


  • In lines 1 and 2 we imported the required package and class.

  • In line 3 we initiated a class Main.

  • In line 7 we initiated an object as Scanner class to use the methods available in it.

  • In line 8 we take the input for its factorial calculation and store it in a variable of int data type.

  • In line 9 we print the returned value by the function call of factorial() with an argument which was already input by the user above.

  • In line 14 we will create a function factorial with 1 input parameter of int data type. Its return type is BigInteger.

  • In line 15 a loop from the input number until >0 continues.

  • In line 16 we calculated the BigInteger value of every value of i from n to 1 using BigInteger.valueof(). Then we multiplied that BigInteger value to the BigInteger value previously present in f using the BigInteger.multiply() method.

  • In line 17 after termination of the loop, the factorial() function returns the value of the last multiplication that happened in the loop.



View all Courses

Keep Exploring