Skip to content

Instantly share code, notes, and snippets.

@gingeleski
Created February 8, 2015 23:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gingeleski/87f65aa5e0499b714486 to your computer and use it in GitHub Desktop.
Save gingeleski/87f65aa5e0499b714486 to your computer and use it in GitHub Desktop.
Fibonacci sequence with and without recursion.
# Fibonacci sequence with and without recursion
def fibs(num) # Not recursive
return num if num <= 1
fib = 1
fib_prev = 1
count = 2
while count < num
count += 1
temp = fib
fib += fib_prev
fib_prev = temp
end
return fib
end
def fibs_rec(num) # Recursive
return num if num <= 1
fib_rec(num - 1) + fib_rec(num - 2)
end
# EXAMPLES
puts fibs(0) # => 0
puts fibs(5) # => 5
puts fibs_rec(1) # => 1
puts fibs_rec(10) # => 55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment