Skip to content

Instantly share code, notes, and snippets.

@jcdavison
Last active August 29, 2015 14:02
Show Gist options
  • Save jcdavison/e2b9edf142796df179d8 to your computer and use it in GitHub Desktop.
Save jcdavison/e2b9edf142796df179d8 to your computer and use it in GitHub Desktop.
examples of iterative and recursive fibonacci
# n 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
# fib(n) 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
# iterative solution
def fib(n)
return n if n == 0 || n == 1
fibs = [0,1]
(n - 2).times do
temp_fib = fibs.reduce(:+)
fibs[0] = fibs[1]
fibs[1] = temp_fib
end
fibs.reduce(:+)
end
# recursive solutions
# If I give this n, it does 2^n units of work
def fib(n)
return 0 if n == 0
return 1 if n == 1
return fib(n - 1) + fib(n - 2)
end
# If I give this n, it does n units of work
def fib(n, indentation = 0)
# puts " " * indentation + "fib(#{n})"
return 0 if n == 0
return 1 if n == 1
return fib(n - 1, indentation + 1) + fib(n - 2, indentation + 1)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment