Created
February 8, 2015 23:21
-
-
Save gingeleski/87f65aa5e0499b714486 to your computer and use it in GitHub Desktop.
Fibonacci sequence with and without recursion.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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