1
import sys

num = long(raw_input("Enter the number for the factorial -> "))
sys.setrecursionlimit(num + 1)


def fact(n):
    if n == 0 or n == 1:
        return 1
    else:
        return (n * fact(n - 1))


print fact(long(num))

Above is the code I used for finding factorial and since the maximum recursion limit depth is '997', I tried to change that using :-

import sys
sys.setrecursionlimit()

But it still gives error. What else can I do ?

LITDataScience
  • 380
  • 5
  • 14
  • 1
    The recursion limit is not an exact science; there is more to the stack than just the Python function being executed. You would need to add an overhead. – Martijn Pieters Sep 19 '17 at 14:25
  • 1
    Use an [iterative solution](https://stackoverflow.com/questions/5136447/function-for-factorial-in-python) instead – Cory Kramer Sep 19 '17 at 14:25

2 Answers2

3

The calling frame also counts. For fact(10), you need 11 frames. Passing in a long integer causes some additional work further down the line, requiring another frame. Add two to the count:

sys.setrecursionlimit(num + 2)

Add more if you have other frames calling the code calling the fact() function. Note that there really is no point in calling long() on the input first; Python will produce a long object if needed automatically.

That said, I'd not muck with the recursion limit. Set it to a high value once, perhaps, but don't keep adjusting it.

A better idea is to not use recursion:

def fact(n):
    num = 1
    while n > 1:
        num *= n
        n -= 1
    return num

or better still, don't re-invent the wheel and use math.factorial() instead. From Python 3.2 onwards, the Python implementation uses a binary split factorial algorithm (plus a table for the first 21 or so results).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • To run the code in the example, you need one more frame for `long` (that's where the mystery frame was coming from). – Jared Goguen Sep 19 '17 at 14:31
  • @JaredGoguen: No, because `long()` has already returned before `fact()` is invoked. – Martijn Pieters Sep 19 '17 at 14:36
  • @JaredGoguen: ah, but that does muck with the stack elsewhere as values are converted. I can reproduce with `long100 = 100L` then `sys.setrecursionlimit(101)` and `fact(long100)`. – Martijn Pieters Sep 19 '17 at 14:37
0
import sys

num = long(raw_input("Enter the number for the factorial -> "))
sys.setrecursionlimit(num + 1)


def fact(n):
    if n == 0 or n == 1:
        return 1
    else:
        return (n * fact(n - 1))


print
print "Factorial is -> ", fact(int(num))

This works perfectly and we can increase the limit > 997

LITDataScience
  • 380
  • 5
  • 14
  • Sorry, you can only mark *one* of the answers as accepted, not both. It's fine if you feel your own post is the one that should have the accept mark, the choice is yours and yours alone. – Martijn Pieters Sep 26 '17 at 09:30