I would like to create this function without recursion.
def fib2(n: int) -> int:
if(n <= 0): return 0
if(n <= 2): return n
return ((fib2(n-1) * fib2(n-2)) - fib2(n-3))
Can anyone help me or explain how to solve this?
I would like to create this function without recursion.
def fib2(n: int) -> int:
if(n <= 0): return 0
if(n <= 2): return n
return ((fib2(n-1) * fib2(n-2)) - fib2(n-3))
Can anyone help me or explain how to solve this?
One rather concise and Pythonic way to do it without any extra space requirements:
def fib2(n: int) -> int:
a, b, c = 0, 1, 2
for _ in range(n):
a, b, c = b, c, (c * b) - a
return a
You need to keep track of three values for the calculation and just keep rotating through them.
Find all the fib2 results from 1 to nn.
def fib2(nn: int) -> int:
mem = {
0: 0, # first if
1: 1, # second if
2: 2 # second if
}
# now find all the fib2 results from 3 to nn
kk = 3
while ( kk <= nn ) :
mem[kk] = mem[kk-1] * mem[kk-2] - mem[kk-3]
kk++;
return mem[nn]