Factorial of a number using Recursion

Factorial of a number is defined as the product of natural numbers starting from 1 to the number that we want to find factorial for. Mathematically, it is defined as follows.

n! = 1*2*3*4* . . . . . .*(n-1)*n

For example, 5!= 1*2*3*4*5=120

Algorithm or Mathematical Generating Function can be written as follows.

f(n)= 1                    if n=0;
f(n)= n*f(n-1)             if n>0;

It is very easy to transform above algorithm or generating function into program that uses Recursion. Below one is the implementation in Java.

Factorial of a given number using Recursion in Java

Here is the implementation for  Factorial of a number using recursion

package com.jminded.recursion;

public class FactorialUsingRecursion {

	/**
	 * <p>Factorial using Recursion</p>
	 * @author Umashankar
	 * {@link https://jminded.com}
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.out.println(factorial(3));
		System.out.println(factorial(0));
		System.out.println(factorial(-7));

	}
	/**
	 * Recursion :: A method calls to it self
	 * <p>Mathematical defintion of factorial</p>
	 * 
	 * 		f(n)= 1          if  n=0;
	 * 		f(n)= n*f(n-1)   if  n>0;
	 * 
	 * @param n
	 */
	public static int factorial(int n){
		//base case
		if(n==0)
			return 1;
		//recursive case
		else if(n>0)
			return n*factorial(n-1);
		//for negative numbers and non integers factorial is undefined.
		else
			return -1;
	}

}

Leave a Comment