Sha256: 2fbe68498b8f691e82b36d6db93bbf15d3a74f67b3d2736e1fe96e2749b44673

Contents?: true

Size: 724 Bytes

Versions: 7

Compression:

Stored size: 724 Bytes

Contents

autoload :Matrix, 'matrix'

module CompSci
  module Fibonacci
    def self.classic(n)
      n < 2 ? n : classic(n-1) + classic(n-2)
    end

    def self.cache_recursive(n, cache = {})
      return n if n < 2
      cache[n] ||= cache_recursive(n-1, cache) + cache_recursive(n-2, cache)
    end

    def self.cache_iterative(n)
      cache = [0, 1]
      2.upto(n) { |i| cache[i] = cache[i-1] + cache[i-2] }
      cache[n]
    end

    def self.dynamic(n)
      a, b = 0, 1
      n.times { a, b = b, a+b }
      a
    end

    # https://gist.github.com/havenwood/02cf291b809327d96a3f
    # slower than dynamic until around n == 500
    def self.matrix(n)
      (Matrix[[0, 1], [1, 1]] ** n.pred)[1, 1].to_i
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
compsci-0.3.3.1 lib/compsci/fibonacci.rb
compsci-0.3.2.4 lib/compsci/fibonacci.rb
compsci-0.3.2.3 lib/compsci/fibonacci.rb
compsci-0.3.2.1 lib/compsci/fibonacci.rb
compsci-0.3.1.1 lib/compsci/fibonacci.rb
compsci-0.3.0.1 lib/compsci/fibonacci.rb
compsci-0.2.0.1 lib/compsci/fibonacci.rb