问题
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