DEV Community

Discussion on: Challenge: Write the recursive Fibonacci algorithm in a different language.

Collapse
 
dwd profile image
Dave Cridland
def fib(arg):
  curr, prev = 1, 1
  n = int(arg)
  if n != arg or n <= 0:
    raise ValueError("Argument must be positive integer")
  if n <= 2:
    return 1
  for count in range(n - 2):
    curr, prev = curr + prev, curr
  return curr

Quick bit of Python. The error handling probably isn't complete, but Python has the useful benefit here that it has native, transparent, Big Number support - you can do fib(10000) if you want (or much higher if you have the memory).

But yeah, I just noticed Douglas wanted a recusrive algorithm, whereas I've done it iteratively without thinking. In general, iterative solutions will execute faster - though this isn't always the case.