0

Hello everyone I made a recursive factorial to compare it with a normal one and the problem is that it only reaches the number 5 and there it gets corrupted

Error: RecursionError: maximum recursion depth exceeded while calling a Python object

import time

def factorial(n):
    res=1
    while n>1:
        res*=n
        n-=1
    return res

def factorial_r(n):
    print(n)
    if n==1:
        return 1
    return n*factorial_r(n-1)

if __name__=="__main__":
    n=1000
    c=time.time()
    factorial(n)
    f = time.time()
    print(f-c)

    c =time.time()
    factorial_r(n)
    f = time.time()
    print(f-c)

It's factorial_r Is there something that I am not understanding well? something i did wrong?

Jsjsue
  • 3
  • 1
  • Does this answer your question? [Recursion limit gives error in factorial function](https://stackoverflow.com/questions/46302998/recursion-limit-gives-error-in-factorial-function) – DarrylG Apr 11 '21 at 03:20

1 Answers1

1

I don't know which version of Python you're using, but the problem is Python does have a recursion limit. Meaning, the stack depth is limited. That is actually a useful feature to avoid accidental infinite recursion loops.

See What is the maximum recursion depth in Python, and how to increase it?

Where they suggest

import sys
sys.setrecursionlimit(1500)
ubershmekel
  • 11,864
  • 10
  • 72
  • 89