1
import sys
sys.setrecursionlimit(1000000000)

def F(n):
    if n == 1:
        return 1
    if n > 1:
        return n * F(n - 1)
print(F(2023)/F(2020))

When the recursion is increased with setrecursionlimit, the following error is returned.

Process finished with exit code -1073741571 (0xC00000FD)

But without increasing the recursion, this code does not work.

How can I fix it?

Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44
alexunder
  • 13
  • 3
  • This related [question](https://stackoverflow.com/questions/20629027/process-finished-with-exit-code-1073741571) on SO might help. – Remi Cuingnet Jan 17 '23 at 13:22
  • 1
    Welcome to Stack Overflow. I can see multiple different ways to interpret the question; each one has been asked before. But regarding the error message specifically, the short version is that `sys.setrecursionlimit` is not a magic bullet - there's a reason the default limit exists in the first place, which is that recursion uses a special region of memory ("the stack") which is fairly limited. – Karl Knechtel Jan 17 '23 at 13:41
  • Why calculate a large factorial simply to cancel most of it? The final result is equivalent to `math.prod(n for n in range(2021,2024))` – John Coleman Jan 17 '23 at 15:27

1 Answers1

1

You can increase the recursion up to 2500 since your factorial is less than 2500:

import sys
sys.setrecursionlimit(2500)

def F(n):
    if n == 1:
        return 1
    if n > 1:
        return n * F(n - 1)

But, when you run above code you will get:

enter image description here

Link to doc: doc

So, you have to increase the limit by:

import sys
sys.set_int_max_str_digits(0)

Now, your code will run:

print(F(2023)/F(2020))

8266912626.0

Alternatively, there is another way;

you can use the built in factorial from math module. But, you have to increase the integer limit:

import sys
sys.set_int_max_str_digits(0)
from math import factorial as F
print(F(2023)/F(2020))

#8266912626.0
Talha Tayyab
  • 8,111
  • 25
  • 27
  • 44