Factorial Program in Java

  • 0
In mathematics, the factorial of the number is defined as

n! = n*(n-1)*(n-2)*(n-3)*(n-4)*...1

Java program to calculate the factorial of a number recursively is given below.
package MathUtility;

class FactorialIterative
{
 public static void main(String args[])
 {
  int num,i;
  long fact=1;
  
  if(args.length==0)
  {
   System.out.println("No Input Provided");
  }
  else
  {
   num=Integer.parseInt(args[0]);
   
   for(i=2;i<=num;i++)
   {
    fact = fact * i;
   }
   
   System.out.println("Factorial of " + num + " is " + fact);
  }
 }
}

To compile the program, write
javac -d . FactorialIterative.java


To run,
java MathUtility.FactorialIterative 5

No comments:

Post a Comment