You are here

Java program to find factorial

Java program to find factorial of a number: entered number is checked first if it is negative, then an error message is printed. You can also find factorial using recursion, in the code the variable fact is an integer so only factorial of small numbers will be correctly displayed, which fits in 4 bytes. For large numbers you can use long data type.

Java programming code

  1. import java.util.Scanner;
  2.  
  3. class Factorial
  4. {
  5.    public static void main(String args[])
  6.    {
  7.       int n, c, fact = 1;
  8.      
  9.       System.out.println("Enter an integer to calculate it's factorial");
  10.       Scanner in = new Scanner(System.in);
  11.      
  12.       n = in.nextInt();
  13.      
  14.       if (n < 0)
  15.          System.out.println("Number should be non-negative.");
  16.       else
  17.       {
  18.          for (c = 1; c <= n; c++)
  19.             fact = fact*c;
  20.      
  21.          System.out.println("Factorial of "+n+" is = "+fact);
  22.       }
  23.    }
  24. }

Output of program:
Java factorial program output

Download Factorial program class file.

Java program for calculating factorial of large numbers

Above program does not give correct result for calculating factorial of say 20. Because 20! is a large number and can't be stored in integer data type which is of 4 bytes. To calculate factorial of say hundred we use BigInteger class of java.math package.

  1. import java.util.Scanner;
  2. import java.math.BigInteger;
  3.  
  4. class BigFactorial
  5. {
  6.   public static void main(String args[])
  7.   {
  8.     int n, c;
  9.     BigInteger inc = new BigInteger("1");
  10.     BigInteger fact = new BigInteger("1");
  11.    
  12.     Scanner input = new Scanner(System.in);
  13.  
  14.     System.out.println("Input an integer");
  15.     n = input.nextInt();
  16.  
  17.     for (c = 1; c <= n; c++) {
  18.       fact = fact.multiply(inc);
  19.       inc = inc.add(BigInteger.ONE);
  20.     }
  21.  
  22.     System.out.println(n + "! = " + fact);
  23.   }
  24. }

Download Big Factorial class file.

We run the Java program to calculate 100 factorial and the following output is obtained.

  1. Input an integer
  2. 100
  3. 100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000