Understanding the Fibonacci sequence

…衆ロ難τιáo~ 提交于 2019-11-28 12:57:38

问题


I have an algorithm that I found online that calculates the Fibonacci sequence. I feel a bit like a fool but I have no idea how it works!

 def fib(n)

  if n == 0 || n == 1
   return n
  end

  if n >= 2
    return fib(n-1) + fib(n-2)
  end
 end

If I call the method with the argument of 10 why does it not return 18? I assume some recursion is happening here but I have no idea. Can someone help me understand this?


回答1:


Let's look at fib(4), according to your code above:

fib(4) #=> 3

It does so by using the following results:

fib(4) #calculates fib(3) + fib(2)
fib(3) #calculates fib(2) + fib(1)
fib(2) #calculates fib(1) + fib(0)
fib(1) #returns 1
fib(0) #returns 0

Crudely speaking your method uses the above results in the following fashion (note: below I am using math-notation (not code) and some dubious spacing to illustrate which bits are being substituted with the results from above):

# fib(4) =   fib(3)                       +  fib(2)
#        = ( fib(2)            + fib(1))  + (fib(1) + fib(0))
#        = ((fib(1) + fib(0))  + 1     )  + (1      + 0     )
#        = ((1      + 0     )  + 1     )  +  1
#        = ( 1                 + 1     )  +  1
#        =   2                            +  1
#        =   3

Your algorithm goes through the above steps. Similarly for fib(10), although it's hardly worth going through it manually as it can be quite cumbersome. As long as you get the basic idea, move on. And by the way you're not a fool, you're just trying to get better at something which is what many of us are trying to do as well. Good luck.



来源:https://stackoverflow.com/questions/38580523/understanding-the-fibonacci-sequence

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!