I know my simple version of a Python Fibonacci algorithm has a time complexity of O(2^n)^2:
def fibonacci_naive(n):
if n < 0:
return None
if n == 0 or n == 1:
return 0
if n == 2:
return 1
return fibonacci_naive(n - 1) + fibonacci_naive(n - 2)
I'm trying to write another Fibonacci recursion, but with O(n) complexity instead. So far I can think of the how to do this with a simple for loop but I'm having trouble wrapping my head around how I can turn it into a recursive function instead. Any help is appreciated!
def fibonacci_fast(n):
if n < 0:
return None
if n == 0 or n == 1:
return 0
if n == 2:
return 1
fn_minus_2 = 0
fn_minus_1 = 1
for _ in range(2, n+1):
temp = fn_minus_2 + fn_minus_1
fn_minus_2 = fn_minus_1
fn_minus_1 = temp
return fn_minus_1
def fibonacci_fast(n, fn_minus_1=1, fn_minus_2=0):
if n < 0:
return None
if n == 0 or n == 1:
return 0
if n == 2:
return 1
return fibonacci_fast(???)