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?

8
  • can you please provide expected output? Commented Dec 3, 2020 at 17:49
  • 2
    A recursive call repeats the same code, but with different arguments. So, you need a loop (to repeat the execution of the same code) and variables which hold values sent to the loop and results from the loop. Commented Dec 3, 2020 at 17:50
  • @ch2019 fib2(7) == 37 Commented Dec 3, 2020 at 17:51
  • @barmar How is this a duplicate? Commented Dec 3, 2020 at 17:52
  • Oh, I thought this was fibonacci, but it's some weird variation of it. Commented Dec 3, 2020 at 17:54

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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]

1 Comment

Exercise to OP : you can do it in constant memory :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.