Skip to content

Instantly share code, notes, and snippets.

@combusean
Created December 18, 2013 08:41
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 combusean/8019164 to your computer and use it in GitHub Desktop.
Save combusean/8019164 to your computer and use it in GitHub Desktop.
Fibonacci sequences in an iterative and recursive manner in Ruby
class Fib
@tracking = [0,1]
def self.iter_compute(index)
tracking = [0,1]
index.times do |i|
tracking << tracking[-2] + tracking[-1]
tracking.shift if tracking.size > 2
end
return tracking[-2]
end
def self.compute(index)
if @tracking[index].nil?
@tracking[index] = compute(index - 1) + compute(index - 2)
else
@tracking[index]
end
end
end
p Fib.iter_compute(7500)
#p Fib.compute(7500)
p [Fib.compute(0), Fib.compute(0) == 0]
p [Fib.compute(1), Fib.compute(1) == 1]
p [Fib.compute(5), Fib.compute(5) == 5]
p [Fib.compute(6), Fib.compute(6) == 8]
p [Fib.compute(10), Fib.compute(10) == 55]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment