JB Header
How to compute Factorial using a recursive algorithm in Java
Introduction This tutorial starts with explaining the basic factorial calculation formula. It then shows how the factorial formula is recursive in nature. Next we will look at how to implement factorial formula in Java in a recursive manner and then explains the code in detail. What is Factorial value of a number Factorial for any number N is equivalent to N * N-1 * N-2...1. I.e. 'N' multiplied by 'N-1' multiplied by 'N-2' and so on till '1'.

Recursive nature of the factorial algorithm To understand how factorial calculation is recursive in nature, let us first define a function factorial such that
factorial(N) = N * N-1 * N-2...1
The above function can also be represented as -
factorial(N)= N * factorial(N - 1)
The above definition is a recursive function as the function calls itself. Let us now write the same recursive logic in Java.
Java code for implementing factorial calculation recursively
Recursive factorial calculation
package com.javabrahman.commonprograms;
 public class Factorial {
   public static long factorial(long number){
     if(number==1){
       return 1;//factorial of 1 is 1
     }else{
       return number*factorial(number-1);//recursive call
    }
  }
  public static void main(String args[]){
    System.out.println("Factorial of 6 is "+factorial(6));
    System.out.println("Factorial of 10 is "+factorial(10));
  }
}
 OUTPUT of the above code
Factorial of 3 is 6
Factorial of 10 is 3628800
Explanation of the code
  • factorial() method is recursive i.e it calls itself in order to compute the factorial value of the number passed to it.
  • Boundary condition for the recursive call is 1 i.e. when in the recursive call for factorial of 1 is made then it does not lead to another recursive call. Instead it returns a constant value 1.
  • In one of the examples specified in the main() method a call to factorial(3) is made. Internally the following calls are made to compute factorial of 3 (3 recursive calls are shaded with three different colors) - Factorial of 3 (which calls factorial of 2(which calls factorial of 1 and returns 1) which returns 2*1 ie. 2) which returns 3 *2 i.e. 6
  • Factorial of 10 is computed in a similar manner recursively.