How to Write a Java Program to Find the Factorial of a Large Number using BigInteger

Here we have a Java Program to Find the Factorial of a Large Number

The factorial of a positive integer n, which is denoted as n!, is the product of all positive integers less than or equal to n.

That is n! = n * (n-1)*(n-2)*....*3*2*1

The factorial value calculated becomes a large number very quickly and none of the primitive datatypes available in java programming language can handle those values.

In Java in the math package a class is available and it is called as BigInteger. It helps us to perform the calculations involving large integer numbers

Here in this program we are using this BigInteger class.

The logic of calculating the factorial value is same. But we will change the data type in here.

Souce code for Factorial.Java

 1 package example;
 2 import java.math.BigInteger;
 3 
 4 public class Factorial {
 5     public static void main(String[] args) {        
 6         int number = 4;
 7         BigInteger factorial = BigInteger.ONE;
 8 
 9         if( number < 0 )
10             System.out.println("Cant fond the factorial of negative number");
11         else if ( number <= 1 )
12             System.out.printf("%d! = %d",number,factorial);
13         else {
14             for( int counter = number; counter >= 2; counter-- ) {
15                 factorial = factorial.multiply(BigInteger.valueOf(counter));
16             }
17             System.out.printf("%d! = %d",number,factorial);
18         }
19     }
20 }

Watch this video to learn how this works