Skip to content

Instantly share code, notes, and snippets.

@bstolte
Created October 21, 2015 18:17
Show Gist options
  • Save bstolte/a6953ede21d6c238facb to your computer and use it in GitHub Desktop.
Save bstolte/a6953ede21d6c238facb to your computer and use it in GitHub Desktop.
Use Benchmark to test Fibonacci Sequence Using Iteration and Recursion
# use iteration
def iterative_fib(n)
fib = [1, 1]
a = 0
b = 1
n.times do
fib << fib[a] + fib[b]
a += 1
b += 1
end
return fib[n]
end
# use recursion
def recursive_fib(n)
if n == 0
return 0
elsif n == 1
return 1
else
return recursive_fib(n-1) + recursive_fib(n-2)
end
end
# Benchmark
require 'benchmark'
num = 35
Benchmark.bm do |x|
x.report("recursive_fib") { recursive_fib(num) }
x.report("iterative_fib") { iterative_fib(num) }
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment