Search code examples
pythonrecursionfactorial

Recursive Factorial Calculator RecursionError


This recursive factorial calculator runs fine all the way up to an input of 994 when I recieve this error: "RecursionError: maximum recursion depth exceeded in comparison". Can someone please explain what is meant by this? How can there be a maximum amount of recursions? Thanks in advance.

def factorial(x):
    if( x == 0):
        return 1
    else:
        return x * factorial(x - 1)
while True:
    u_input = input("")
    print(factorial(int(u_input)))

def calc_factorial(num):
    num-=1
    fact_total = 1
    while num > 0:
        fact_total *= num
        num-=1
    return(fact_total)

EDIT: I understand that recursion is re-using a function from within that function as a loop but I do not understand what recursion depth is and would like that explained. I could not tell from the answers to the other question. Apologies for the confusion.


Solution

  • The error means what it says: Python limits the depth of how many recursive calls you can make. The default is 1000, which was chosen as a number that means you most likely have infinite recursion somewhere. Since no computer can keep track of an infinite amount of recursive calls (and such a program would never finish anyway), halting with this error message is seen as preferable to recurring as deeply as the computer can handle, which eventually results in a stack overflow.

    You can change this limit if you wish with sys.setrecursionlimit, but the best way to avoid this issue is to change your program to work iteratively instead of recursively. Fortunately, this is easy for a factorial calculation:

    def factorial(x):
        result = 1
        for num in range(1, x+1):
            result *= num
        return result