Tail Recursion Fibonacci

Mat.S picture Mat.S · Mar 1, 2014 · Viewed 22.9k times · Source

How do I implement a recursive Fibonacci function with no loops running in O(n)?

Answer

DaoWen picture DaoWen · Mar 1, 2014

Typically I'd be against posting an answer to a homework question like this, but everything posted so far seems to be overcomplicating things. As said in the comments above, you should just use recursion to solve the problem like you would do iteratively.

Here's the iterative solution:

def fib(n):
  a, b = 0, 1
  while n > 0:
    a, b = b, a+b
    n -= 1
  return a

Here's an equivalent recursive solution:

def fib(n):
  def fib_help(a, b, n):
    return fib_help(b, a+b, n-1) if n > 0 else a
  return fib_help(0, 1, n)

Note that in both cases we actually compute up to Fn+1, but return Fn as the result. This fits nicely with the "hint" you were given.

I hope that you'll take the time to compare the two solutions and convince yourself that they're equivalent. Understanding how to transform an iterative solution to an equivalent recursive one (or vice versa) is a good skill to develop.