Reputation: 9
Can someone please explain to me why the final return value from the following recursive function is CORRECT?
function(factorial) {
if (n == 0)
return 1;
return n * factorial (n -1);
}
I understand the recursion, but I don't understand why the return value is the the correct result, instead of just 1.. If I change the return to 2, then it simply doubles the result of factorial. So it seems whatever value I put in that return expression becomes a multiplier for the accumulated result of the factorial function..Why is this so? How is the accumulated result of the factorial function stored? All replies appreciated
Upvotes: 0
Views: 96
Reputation: 9
Thanks for all of your answers guys - Frogattos' answer was probably the one that really raised my understanding;
factorial(5)
factorial(5) = 5 * factorial(4)
factorial(5) = 5 * 4 * factorial(3)
factorial(5) = 5 * 4 * 3 * factorial(2)
factorial(5) = 5 * 4 * 3 * 2 * factorial(1)
factorial(5) = 5 * 4 * 3 * 2 * 1 * factorial(0)
factorial(5) = 5 * 4 * 3 * 2 * 1 * 1
Cheers!
Upvotes: 0
Reputation: 29285
You can simply unfold a factorial(5)
.
factorial(5)
factorial(5) = 5 * factorial(4)
factorial(5) = 5 * 4 * factorial(3)
factorial(5) = 5 * 4 * 3 * factorial(2)
factorial(5) = 5 * 4 * 3 * 2 * factorial(1)
factorial(5) = 5 * 4 * 3 * 2 * 1 * factorial(0)
factorial(5) = 5 * 4 * 3 * 2 * 1 * 1
Upvotes: 3
Reputation: 1009
Imagine input as 5.Then the final result of first function call will be like,
Edited as per @gurvinder372's comment:
return 5*(return 4 * ( return 3 * (return 2 * ( return 1 * ( return 1)))))
Upvotes: 2
Reputation: 68393
Just dry-run
the method like this
function factorial (n) { //line 1
if (n == 0) //line 2
return 1;//line 3
return n * factorial (n -1);//line 4
}
say n = 3
, and factorial(3)
is being called, it will go through 4
recursions (function calls for factorial(n)
)
Recursion 1
n = 3, line 2 condition fails so it goes to line 4 and return 3 * factorial(2)
Recursion 2
n = 2, line 2 condition fails so it goes to line 4 and return 2 * factorial(1)
Recursion 3
n = 1, line 2 condition fails so it goes to line 4 and return 1 * factorial(0)
Recursion 4
n = 0, line 2 condition succeeds now, so it goes to line 3 and return 1
. Now it will return to the function call in recursion 3 and it will replace 1 * factorial(0)
with 1 * 1
and will finally return 3 * 2 * 1 * 1
when returned to first recursion call and return the single value.
It means if you were returning 2
in line 2 then everything got multiplied with 2
.
Simple isn't it :)
Upvotes: 3
Reputation: 10282
Draw one stack (First In Last Out) structure and see the execution of your function with its return values every time. After execution of every step pop the block from it. Now you can see the values returned by previously called block to currently called block.
Note: Here is block is nothing but your recursive function.
Upvotes: -1