Ruby Fibonacci algorithm

前端 未结 5 703
北荒
北荒 2020-11-29 09:14

The following is a method I wrote to calculate a value in the Fibonacci sequence:

def fib(n)

    if n == 0
        return 0
    end
    if n == 1
        re         


        
5条回答
  •  萌比男神i
    2020-11-29 09:21

    I tried comparing the run time of two fibonacci methods on repl.it

    require 'benchmark'
    
    def fib_memo(n, memo = {})
      if n == 0 || n == 1
        return n
      end
      memo[n] ||= fib_memo(n-1, memo) + fib_memo(n-2, memo)
    end
    
    
    def fib_naive(n)
      if n == 0 || n == 1
        return n
      end
      fib_naive(n-1) + fib_naive(n-2)
    end
    
    def time(&block) 
      puts Benchmark.measure(&block) 
    end
    
    time {fib_memo(14)}
    time {fib_naive(14)}
    

    Output

    0.000000   0.000000   0.000000 (  0.000008)
    0.000000   0.000000   0.000000 (  0.000099)
    

    As you can see, the runtime is quite different. As @Uri Agassi suggested, use memoization. The concept is explained quite well here https://stackoverflow.com/a/1988826/5256509

提交回复
热议问题