Initial commit, first 27 tasks
[project-euler.git] / fibonacci.rb
1 class Integer
2 # Return the self'th Fibonacci number
3 def fibonacci_slow
4 return self if self <= 1
5 return 1 if self == 2
6 f2 = 0 # the n-2th term
7 f1 = 1 # the n-1th term
8 f0 = 1
9 3.upto(self) do |i|
10 f0, f1, f2 = f0 + f1, f0, f1
11 end
12 f0
13 end
14
15 @@fibonacci_cache = {0 => 0, 1 => 1, 2 => 1}
16 def fibonacci
17 unless @@fibonacci_cache.has_key?(self)
18 @@fibonacci_cache[self] = ((self - 2).fibonacci + (self - 1).fibonacci)
19 end
20 @@fibonacci_cache[self]
21 end
22 end