How to use the BigInteger class to calculate factorials in Java
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.
Example
The factorial of 100 is:
100!=93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
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 thisBigIntegerwith the passedBigInteger. - The
BigInteger.valueof()method gives aBigIntegerwhose value is equal to the value of long passed as parameter.
Code
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(System.in);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
Explanation
-
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
Scannerclass 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
intdata 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
intdata type. Its return type isBigInteger. -
In line 15 a loop from the input number until
>0continues. -
In line 16 we calculated the
BigIntegervalue of every value ofifromnto1usingBigInteger.valueof(). Then we multiplied thatBigIntegervalue to theBigIntegervalue previously present infusing theBigInteger.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.