I\'m trying to implement the following function, but it keeps giving me the stack level too deep (SystemStackError) error.
Any ideas what the problem mi
Linear
module Fib
def self.compute(index)
first, second = 0, 1
index.times do
first, second = second, first + second
end
first
end
end
Recursive with caching
module Fib
@@mem = {}
def self.compute(index)
return index if index <= 1
@@mem[index] ||= compute(index-1) + compute(index-2)
end
end
Closure
module Fib
def self.compute(index)
f = fibonacci
index.times { f.call }
f.call
end
def self.fibonacci
first, second = 1, 0
Proc.new {
first, second = second, first + second
first
}
end
end
None of these solutions will crash your system if you call Fib.compute(256)