Recursive factorial method in Java


The factorial of any non-negative integer is basically the product of all the integers that are smaller than or equal to it. The factorial can be obtained using a recursive method.

A program that demonstrates this is given as follows:

Example

 Live Demo

public class Demo {
   public static long fact(long n) {
      if (n <= 1)
         return 1;
      else
         return n * fact(n - 1);
   }
   public static void main(String args[]) {
      System.out.println("The factorial of 6 is: " + fact(6));
      System.out.println("The factorial of 0 is: " + fact(0));
   }
}

Output

The factorial of 6 is: 720
The factorial of 0 is: 1

Now let us understand the above program.

The method fact() calculates the factorial of a number n. If n is less than or equal to 1, it returns 1. Otherwise it recursively calls itself and returns n * fact(n - 1). A code snippet which demonstrates this is as follows:

public static long fact(long n) {
   if (n <= 1)
      return 1;
   else
      return n * fact(n - 1);
}

In main(), the method fact() is called with different values. A code snippet which demonstrates this is as follows:

public static void main(String args[]) {
   System.out.println("The factorial of 6 is: " + fact(6));
   System.out.println("The factorial of 0 is: " + fact(0));
}

Rishi Raj
Rishi Raj

I am a coder

Updated on: 30-Jul-2019

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements