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
Java code for implementing factorial calculation recursively
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.