0

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?

2 Answers2

1

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.

user2390182
  • 72,016
  • 6
  • 67
  • 89
0

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]
napuzba
  • 6,033
  • 3
  • 21
  • 32