Factorial is often used as an example of something which can be performed using recursion.
For example, factorial of 5 is calculated as follows:
5! = 5 * 4 * 3 * 2 * 1
Also, there is another way of thinking about it:
5! = 5 * 4!
4! = 4 * 3!
3! = 3 * 2!
2! = 2 * 1!
1! = 1
The way the second series of equalities are written, it can be seen that a factorial can be calculated in a recursive fashion. For example:
5! = 5 * 4! --> 5! = 5 * (4 * 3!) --> 5! = 5 * (4 * (3 * 2!)) --> and so on.
The fact
function in the question is performing the factorial function as written in the second series of equalities:
fact(n) = n * fact(n-1);
So, when the fact
method is being called, way it is being called can be thought as something like the following:
fact(5) --> fact(5 * fact(4)) --> fact(5 * fact(4 * fact(3))) --> and so on.
Also, it should be noted as Kip points out in the comments, calculating the factorial of a number can be much easily and quickly calculated by iterating over the range of numbers from n
to 1
and multiplying it together to calculate the result.