11

Interesting topic of recursion and stack overflow in class today and I wondered if there is any way of increasing the maximum recursion depth in Python? Wrote a quick function for finding the factorial of n using recursion:

def factorial(n):
    if n == 1:
        return n
    else:
        return n * factorial(n-1)

It can cope with factorial(994) but not factorial(995). The error given is:

RuntimeError: maximum recursion depth exceeded in comparison

Obviously a higher factorial can be found iteratively but, for the sake of argument and intrigue, can the maximum recursion depth be increased?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Rob Murray
  • 1,773
  • 6
  • 20
  • 32
  • 1
    https://docs.python.org/2/library/sys.html#sys.setrecursionlimit – freakish Nov 17 '15 at 13:04
  • 5
    Note that the standard way of avoiding too much recursion here is to use memoization. – Daniel Roseman Nov 17 '15 at 13:05
  • 2
    Nope, there is no hate in here. We all are here to help others. Closing as a dupe doesn't mean that we *hate* you. All the best in future. – Bhargav Rao Nov 17 '15 at 13:17
  • If implementing factorial program using recursion is necessary. You can implement it in following manner which is able to find factorial without any limit using python. https://drive.google.com/file/d/1A0z9eyXD5mNIAZRotX5RM2QAu9bbZqHa/view?usp=drivesdk –  May 16 '20 at 07:46

2 Answers2

18
import sys

sys.setrecursionlimit(2000)
Ayush
  • 3,695
  • 1
  • 32
  • 42
6
import sys

iMaxStackSize = 5000
sys.setrecursionlimit(iMaxStackSize)
Mangu Singh Rajpurohit
  • 10,806
  • 4
  • 68
  • 97