Search code examples
pythonrecursionlimitfactorial

Factorial function in python is being limited


I made a simple factorial program:

import sys

sys.set_int_max_str_digits(0)
sys.setrecursionlimit(1000000)

def factorial(x):
    if x == 0 | x == 1:
        return 1
    elif x > 1:
        return x * factorial(x - 1)

i = 0
while 1:
    print(factorial(i), '\n')
    i += 1

But after a while the program halts. I want to know if there's a way to remove the limit on how big it could get.


Solution

  • Recursion is not meant to be infinite. Eventually your program would fail, even on a system with a huge amount of memory.

    Also note that the recursion limit given to setrecursionlimit() is not a guarantee that you'll get that recursion depth. To quote from the sys.setrecursionlimit documentation:

    The highest possible limit is platform-dependent. A user may need to set the limit higher when they have a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash.

    I would suggest either limiting the program to calculating a reasonable sized factorial, or not using recursion. Some tasks are much better suited to recursion versus iteration, but factorials is not one of them.