Skip to content

Instantly share code, notes, and snippets.

@KevinSia
Last active April 25, 2019 10:16
Show Gist options
  • Save KevinSia/42fa26b7069105f94dca06d72482ce0f to your computer and use it in GitHub Desktop.
Save KevinSia/42fa26b7069105f94dca06d72482ce0f to your computer and use it in GitHub Desktop.
# OLD SOLUTION
# def fibonacci_iterative(n)
# if n <= 1
# return n
# else
# arr = [0, 1]
# index = 0
# (n - 1).times do
# # arr might get very big if n is a big number
# arr << arr[index] + arr[index + 1]
# index += 1
# end
# return arr[-1]
# end
# end
def fibonacci_iterative(n)
if n <= 1
return n
else
a, b = 0, 1
(n - 1).times do
# b = a + b
# a = b - a
a, b = b, a + b
end
return b
end
end
def fibonacci_recursive(n)
if n <= 1
return n
else
fibonacci_recursive(n - 2) + fibonacci_recursive(n - 1)
end
end
puts fibonacci_iterative(0) == 0
puts fibonacci_iterative(1) == 1
puts fibonacci_iterative(2) == 1
puts fibonacci_iterative(3) == 2
puts fibonacci_iterative(4) == 3
puts fibonacci_iterative(5) == 5
puts fibonacci_iterative(6) == 8
# puts fibonacci_recursive(0) == 0
# puts fibonacci_recursive(1) == 1
# puts fibonacci_recursive(2) == 1
# puts fibonacci_recursive(3) == 2
# puts fibonacci_recursive(4) == 3
# puts fibonacci_recursive(5) == 5
# puts fibonacci_recursive(6) == 8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment