1
votes

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.

3
Possible duplicate of Maximum recursion depth? - Alex Hall
I have seen that- I would like to know what recursion depth is? - Matt

3 Answers

3
votes

Recursive calls are just like any other function calls, and function calls use memory to keep track of the state inside each function. You will notice that you get a very long traceback showing all the nested function calls that are on the stack. Since memory is finite, recursion depth (the number of nested function calls) is inherently limited even without python's enforced limit.

2
votes

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
0
votes

There are built in Function with Math library, It is improved algorithm to get the value of factorial quickly, So when we are writing the recursive algorithm to get the value for factorial, there will be a recursive limit. So If we use the built in library, then we can escape from that problem.

import math
math.factorial(5)

Answer : 120