Sunday, 1 November 2015

Factorial of a number



Factorial of any number is n!.For example,Factorial of 5 is 5*4*3*2*1=120.We can solve the problem either using for loop or recursion.

Input Parameters:- 5

Output:- 120


Sample Program:-


 /**  
  * @author Dixit  
  *   
  */  
 public class FactorialProgram {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           int number = 4;  
           /*  
            * Factorial of any number is! n. For example, factorial of 4 is  
            * 4*3*2*1.  
            */  
           int fact;  
           fact = factorial(number);  
           System.out.println("Factorial of a number :" + fact);  
           fact = factorialUsingRecursion(number);  
           System.out.println("Factorial of a number using recursion:" + fact);  
      }  
      private static int factorialUsingRecursion(int number) {  
           if (number <= 1)  
                // if the number is 1 then return 1  
                return 1;  
           else  
                // else call the same function with the value - 1  
                return number * factorialUsingRecursion(number - 1);  
      }  
      private static int factorial(int number) {  
           int factorial = number;  
           for (int i = (number - 1); i > 1; i--) {  
                factorial = factorial * i;  
           }  
           return factorial;  
      }  
 }  


 Output  
 Factorial of a number :24  
 Factorial of a number using recursion:24  



Enjoy Programming


No comments:

Post a Comment