Java program to find factorial


Java program to find factorial


This java program finds factorial of a number. Entered number is checked first if its negative then an error message is printed.

Java programming code

import java.util.Scanner;
 
class Factorial
{
   public static void main(String args[])
   {
      int n, c, fact = 1;
 
      System.out.println("Enter an integer to calculate it's factorial");
      Scanner in = new Scanner(System.in);
 
      n = in.nextInt();
 
      if ( n < 0 )
         System.out.println("Number should be non-negative.");
      else
      {
         for ( c = 1 ; c <= n ; c++ )
            fact = fact*c;
 
         System.out.println("Factorial of "+n+" is = "+fact);
      }
   }
}
Download Factorial program class file.
Output of program:
factorial program
You can also find factorial using recursion, in the code fact is an integer variable so only factorial of small numbers will be correctly displayed or which fits in 4 bytes. For large numbers you can use long data type.

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 cant 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.
import java.util.Scanner;
import java.math.BigInteger;
 
class BigFactorial
{
  public static void main(String args[])
  {
    int n, c;
    BigInteger inc = new BigInteger("1");
    BigInteger fact = new BigInteger("1");
 
    Scanner input = new Scanner(System.in);
 
    System.out.println("Input an integer");
    n = input.nextInt();
 
    for (c = 1; c <= n; c++) {
      fact = fact.multiply(inc);
      inc = inc.add(BigInteger.ONE);
    }
 
    System.out.println(n + "! = " + fact);
  }
}
Download Big Factorial class file.
We run the above java program to calculate 100 factorial and following output is obtained.
Input an integer
100
100! = 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000
Previous
Next Post »