Skip to content
Advertisement

Java recursive Fibonacci sequence

Please explain this simple code:

JavaScript

I’m confused with the last line especially because if n = 5 for example, then fibonacci(4) + fibonacci(3) would be called and so on but I don’t understand how this algorithm calculates the value at index 5 by this method. Please explain with a lot of detail!

Advertisement

Answer

In fibonacci sequence each item is the sum of the previous two. So, you wrote a recursive algorithm.

So,

JavaScript

Now you already know fibonacci(1)==1 and fibonacci(0) == 0. So, you can subsequently calculate the other values.

Now,

JavaScript

And from fibonacci sequence 0,1,1,2,3,5,8,13,21.... we can see that for 5th element the fibonacci sequence returns 5.

See here for Recursion Tutorial.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement