How to Calculate Factorial of Number using Java with Recursion

Factorial? let me show you how we calculate factorial of given number. Consider requirement that I want to find factorial of number 5.

If you remembered Maths, in School we used to find factorial using below match function !
n! = n * (n-1)!

Ex. 5! = 5*(5-1)! = 5*4!
      4! = 4 *(4-1)! = 4*3!
      3! = 3*(3-1)! = 3*2!
      2!= 2*(2-1)! = 2*1!
      1! = 1*(1-0)! =  1

If we substitute values of factorials then it becomes :
      5! = 5*(5-1)! = 5*4! = 5*24 = 120
      4! = 4 *(4-1)! = 4*3! = 4*6 = 24
      3! = 3*(3-1)! = 3*2! = 6
      2!= 2*(2-1)! = 2*1! = 2
      1! = 1*(1-0)! =  1
Hence 5! = 120.

Using below simple Java program you can achieve same using recursion.

Java Program to Calculate Factorial of Number using Recursion :

package com.anuj.algorithms;

/**
 * 
 * @author Anuj
 *
 */
public class FactorialExample {

 /**
  * @param args
  */
 public static void main(String[] args) {
  FactorialExample obj = new FactorialExample();
  
  int no=5;
  int result = obj.getFactorial(no);
  System.out.println(result);
 }
 
    public int getFactorial(int no){
     System.out.println(no);
     if(no == 1){ 
      return 1;
     }
     no =  no * getFactorial(no-1);
     
     return no;
    } 

}


Output :
120

No comments:

Post a Comment