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:
100!=93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
We will be using the BigInteger
class which has the .multiply()
method and .valueof()
method that we will use in our code.
BigInteger.multiply()
method multiplies this BigInteger
with the passed BigInteger
.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(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
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.
RELATED TAGS
CONTRIBUTOR
View all Courses