require 'benchmark'
class TriBonacci
def initialize
@memo = [1,1,2]
end
def f(n)
return @memo[n] unless @memo[n] == nil
@memo[n] = f(n-1) + f(n-2) + f(n-3)
end
def calc(n)
last = @memo.length - 1
return @memo[n] if n <= last
(last + 1).upto(n-1) do |i|
f(i)
end
f(n)
end
end
n = 6500
Benchmark.bm do |x|
x.report {TriBonacci.new.f(n)}
x.report {TriBonacci.new.calc(n)}
end
cmVxdWlyZSAnYmVuY2htYXJrJwoKY2xhc3MgVHJpQm9uYWNjaQogIGRlZiBpbml0aWFsaXplCiAgICBAbWVtbyA9IFsxLDEsMl0KICBlbmQKICBkZWYgZihuKQogICAgcmV0dXJuIEBtZW1vW25dIHVubGVzcyBAbWVtb1tuXSA9PSBuaWwKICAgIEBtZW1vW25dID0gZihuLTEpICsgZihuLTIpICsgZihuLTMpCiAgZW5kCiAgZGVmIGNhbGMobikKICAgIGxhc3QgPSBAbWVtby5sZW5ndGggLSAxCiAgICByZXR1cm4gQG1lbW9bbl0gaWYgbiA8PSBsYXN0CiAgICAobGFzdCArIDEpLnVwdG8obi0xKSBkbyB8aXwKICAgICAgZihpKQogICAgZW5kCiAgICBmKG4pCiAgZW5kCmVuZAoKbiA9IDY1MDAKQmVuY2htYXJrLmJtIGRvIHx4fAogIHgucmVwb3J0IHtUcmlCb25hY2NpLm5ldy5mKG4pfQogIHgucmVwb3J0IHtUcmlCb25hY2NpLm5ldy5jYWxjKG4pfQplbmQKCiAgICA=