Skip to content

Instantly share code, notes, and snippets.

@AndrewGuard
Last active January 2, 2016 21:49
Show Gist options
  • Save AndrewGuard/8365690 to your computer and use it in GitHub Desktop.
Save AndrewGuard/8365690 to your computer and use it in GitHub Desktop.
def fib_iterative(n)
current = 0
successor = 1
n.times do |n|
current, successor = successor, current + successor
end
return current
end
def fib_recursive(n)
return n if n <= 1
fib_recursive( n - 1 ) + fib_recursive( n - 2 )
end
def benchmark
start = Time.now
yield
Time.now - start
end
#test code
puts fib_iterative(0) == 0
puts fib_iterative(1) == 1
puts fib_iterative(2) == 1
puts fib_iterative(3) == 2
puts fib_iterative(4) == 3
puts fib_iterative(5) == 5
puts fib_recursive(0) == 0
puts fib_recursive(1) == 1
puts fib_recursive(2) == 1
puts fib_recursive(3) == 2
puts fib_recursive(4) == 3
puts fib_recursive(5) == 5
puts "Recursive " + benchmark {
1000.times {fib_recursive(10)}
}.to_s
puts "Iterative " + benchmark {
1000.times {fib_iterative(10)}
}.to_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment