-1

I have created a simple recursive factorial function in Python. Currently, my computer can calculate factorials up to approximately 10000. For values higher than that, python.exe just stops working.

So, my question is this: if I want to handle larger factorials, is there any way I can do this (by using multiple cores, etc)? Or is it just Python's limit? I've checked out using the GPU for Python scripts, but the method seems to complicated + convoluted for what I have in mind.

I have set the recursion limit to 100000, so that shouldn't be the issue.

This is my code:

import sys, time
sys.setrecursionlimit(100000)
def f(n):
    if n==0:
        return 1
    else:
        return n*f1(n-1)

Thank you for your help

PK123
  • 43
  • 8
  • 1
    *I have set the recursion limit to 10000000, so that shouldn't be the issue*. Except that all those recursive call frames all take memory. Python doesn't optimise recursive calls. – Martijn Pieters Nov 09 '16 at 15:29
  • Why would you do that ? If you are currently using the whole memory using multiple cores will not change anything – Hearner Nov 09 '16 at 15:29
  • And no, multiple cores won't help, because the Python interpreter has a Global Interpreter Lock that's rather incompatible with multi-core processing. Find a better algorithm instead (preferably without recursion). – Martijn Pieters Nov 09 '16 at 15:30
  • So does python.exe stop working because my memory is overloaded? Why does that happen? – PK123 Nov 09 '16 at 15:37

1 Answers1

0

I think that the main problem is call stack, if you don't use tail recursion on your factorial, stack will be fill. I think that post would be useful for you.

What is tail recursion?

def f_loop(n):
    acum = 1 
    for i in range(2,n+1):
        acum*=i
    return acum

Yo can implement that with functools.reduce.

Community
  • 1
  • 1
mandrewcito
  • 170
  • 8