Saturday, August 10, 2013

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 Factorial {

 /**
  * @param args
  */
 public static void main(String[] args) {
  Factorial factorial = new Factorial();
  
  int result = factorial.fact(5);
  System.out.println(result);
 }
 
    public int fact(int num){
     if(num == 1){ 
      return 1;
     }
     num =  num * fact(num-1);
     return num;
    } 

}

Output :
120

You may be Interested in :
  1. Check number is ArmStrong number or not using Java
  2. Check Number is Palindrom number or not using Java
  3. Java Program to Find Fibonacci Series of Given Number