First you should understand how factorial works.
Lets take 4! as an example.
4! = 4 * 3 * 2 * 1 = 24
Let us simulate the code using the example above:
int fact(int n)
{
int result;
if(n==0 || n==1)
return 1;
result = fact(n-1) * n;
return result;
}
In most programming language, we have what we call function stack
. It is just like a deck of cards, where each card is placed above the other--and each card may be thought of as a function So, passing on method fact
:
Stack level 1: fact(4) // n = 4 and is not equal to 1. So we call fact(n-1)*n
Stack level 2: fact(3)
Stack level 3: fact(2)
Stack level 4: fact(1)
// now, n = 1. so we return 1 from this function.
returning values...
Stack level 3: 2 * fact(1) = 2 * 1 = 2
Stack level 2: 3 * fact(2) = 3 * 2 = 6
Stack level 1: 4 * fact(3) = 4 * 6 = 24
so we got 24.
Take note of these lines:
result = fact(n-1) * n;
return result;
or simply:
return fact(n-1) * n;
This calls the function itself. Using 4 as an example,
In sequence according to function stacks..
return fact(3) * 4;
return fact(2) * 3 * 4
return fact(1) * 2 * 3 * 4
Substituting results...
return 1 * 2 * 3 * 4 = return 24
I hope you get the point.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…