I have this recursive factorial function:
def factorial(n):
if n < 2:
return 1
return n * factorial(n-1)
Doing factorial(998)
works, but factorial(999)
will raise a RecursionError: maximum recursion depth exceeded in comparison
.
Why does it error at factorial(999)
and not 1000
or 1001
? factorial(1)
hits the base case, so there should only be one stack frame from calling the factorial
function, factorial(2)
recurses once, so it should use 2 stack frames and so on.
Is the recursion limit exclusive or inclusive? As in, if you setrecursionlimit(1000)
does it error when you reach 1000 stack frames or when you exceed 1000?
If it's exlusive, why does it error on n=999
instead of n=1000
? n=999
should create 999 frames, not 1000. Where does the extra stack frame come from that makes it hit 1000? If the limit is inclusive, where do the extra 2 stack frames come from that make it hit 1001 stack frames?