def factorial(n):
if n == 0 :
return 1
return n* factorial(n-1)
Here when n reaches 0 the result is 24. Why is the result not 1?
def factorial(n):
if n == 0 :
return 1
return n* factorial(n-1)
Here when n reaches 0 the result is 24. Why is the result not 1?
The best thing to do is to simulate the function on paper.
You called factorial(4)
.
Looking at the definition of the function what should the function do? Since n
is equal to 4, it returns 4 * factorial(3)
.
What does factorial(3)
return? 3 * factorial(2)
so we have 4 * 3 * factorial(2)
. You keep going on this way until factorial(0)
is called.
When you reach factorial(0)
the function simply returns 1 without calling itself again and thus the recursion stops.
As you can see, if you call factorial(0)
the result is 1.
When calling factorial(4)
and the recursion reaches 0 the function returns 1, the call stack unwinds and the multiplications are performed.
Here's a visualization
factorial(4): n != 0, so return 4 * factorial(3)
factorial(3): n != 0, so return 3 * factorial(2)
factorial(2); n != 0, so return 2 * factorial(1)
factorial(1): n != 0, so return 1 * factorial(0)
factorial(0): n == 0 so return 1
factorial(1): 1 * factorial(0) = 1 * 1 = 1
factorial(2): 2 * factorial(1) = 2 * 1 = 2
factorial(3): 3 * factorial(2) = 3 * 2 = 6
factorial(4): 4 * factorial(3) = 4 * 6 = 24