Get factorial of any number in Java Program

By Saruque Ahamed Mollick

Lets first know how to determine the factorial value of a number. Suppose we are to find the factorial value of 5
It will be

5x4x3x2x1=120

Until 1 we will multiply that number in a decreasing order.

Here is a simple Java program which will give you the factorial value of a number in the output.

import java.util.*;
public class factorial {
  public static void main(String[] args) {
    int i,n;int p;
    Scanner scan=new Scanner(System.in);
    System.out.println("Enter Number:");
    n=scan.nextInt();
    scan.close();
    
    
    
    if(n==1) System.out.println(n);
    if (n==0) System.out.println(1);
    if (n>1) {
      p=n*(n-(n-1));
      for(i=2;i<n;i++) {
        p=p*(n-(n-i));
      
    }
      System.out.println(p);
    }
    if (n<1) {
      n=-n;
      p=n*(n-(n-1));
      for(i=2;i<n;i++) {
        p=p*(n-(n-i));
      
    }
      System.out.println(-p);
    }
    
    
  }

}
Enter Number:
8
40320

 

But in this program, if you work with large numbers you will not get the right answer. The reason is your data type.

We took int data type here and int can’t deal with large numbers and thus in case of big numbers data overflow occurs.
So we have to find another program which will be able to work with large numbers/Big Numbers

Java Program to Find the factorial of big/Large Numbers

import java.math.BigInteger;
import java.util.Scanner;

public class factorial {

   public static void main(String[] args) {
       Scanner scan = new Scanner(System.in);
       System.out.print("Enter number: ");
       int n = scan.nextInt();
       String f = factorial1(n);
      
       System.out.println("Factorial is " + f);
   }

   public static String factorial1(int n) {
       BigInteger fact = new BigInteger("1");
       for (int i = 1; i <= n; i++) {
           fact = fact.multiply(new BigInteger(i + ""));
       }
       return fact.toString();
   }
}

BigInteger Class is used to deal with large numbers. Overflow will not occur here.
The loop in this program is similar to the normal factorial program loop. The only difference is the object, We have initialized with the value of 1.
And the final value will be stored in fact and we will display it through

return fact.toString();
By using this BigInteger Class we can find the factorial of large or big numbers in this way.

Output:

Enter number: 29
Factorial is 8841761993739701954543616000000

Feel free to make doubts be cleared in the comment section

Leave a Reply

Your email address will not be published. Required fields are marked *