Created
December 18, 2013 08:41
-
-
Save combusean/8019164 to your computer and use it in GitHub Desktop.
Fibonacci sequences in an iterative and recursive manner in Ruby
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
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