Java Program to Find Factorial of a Number Recursively
Factorial of a number n is defined as a product of all positive descending integers, Factorial of n is denoted by n!. Factorial can be calculated using the following recursive formula where the recursive call is made to a multiplicity of all the numbers lesser than the number for which the factorial is computed as the formula to calculate factorial is as follows:
n! = n * [(n-1)!] i.e factorial of n (n!) = n * (n-1) * ......* 3 * 2* 1
Note: Factorial of 0 is 1
Input : 5! Processing : 5*4*3*2*1 Output : 120
Input : 6! Processing : 6*5*4*3*2*1 Output : 720
Factorial of 5 is :120
Initially, the factorial() is called from the main method with 5 passed as an argument. Since 5 is greater than or equal to 1, 5 is multiplied to the result of factorial( ) where 4 (n -1) is passed. Since, it is called from the same method, it is a recursive call. In each recursive call, the value of argument n is decreased by 1 until n reaches less than 1. When the value of n is less than or equal to 1, then there is no recursive call and at last, it returns 1.
Factorial of 0 is : 1 Factorial of 1 is : 1
Initially, the factorial( ) is called from the main method with 6 passed as an argument. In each recursive call, the value of argument n is decreased by 1 until n reaches less than 1. For 1! decreased argument been passed is 0! as a small recursion call to be computed. As discussed above factorial of zero is 1. Hence, the small answer returned is 1, which later is multiplied to 1 itself so do result 1 as an output. Hence, it is stated when the value of n is less than or equal to 0 then no recursion call is computed as we will encounter negative integers over which factorial is not allowed to be computed.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.