I have been trying to write a Fibonacci series program recursively and I also got the output after searching online.
The code is:
But I am getting confused in the return statement, for example, if n=5 then the return statement will be
Which function is recursively called first? Or is it that the first recursive call gets executed first and after it has returned the final output, the second recursive call gets executed, or maybe both of them are called simultaneously?
When using recursion, a well placed logger can give you a lot of information.
Output: Having said that, I am not sure what the intention of this method is. It says fibonacci, but when I pass 4 to it, it returns 3. Given that fibonacci series are as follows : 0, 1, 1, 2, 3, 5, 8, 13, 21, ... ,
What does the returned value indicate ?
You do realise that naïve Fibonacci calculating technique is notorious for its inefficiency? It runs in exponential time.
I am also not sure I agree with Salvin about what a Fibonacci series contains. I don't believe there s such a thing as fib(0); the first two element of the series are 1, 1. Also, what you have is the classic Fibonacci series; it is possible to start a Fibonacci series with any two numbers.There are other techniques that run in linear time, and Kaldewaij has a solution running in logarithmic time.
Campbell Ritchie wrote:... I am also not sure I agree with Salvin about what a Fibonacci series contains. I don't believe there s such a thing as fib(0); the first two element of the series are 1, 1...
I looked up wiki and found this: Fibonacci_number. They do mention about F0 as a part of the Fibonacci sequence. Is there any particular reason why it's not a good idea to include 0 or consider 0 as F0 ?
Here's what wiki mentions:
wiki wrote:In mathematics, the Fibonacci numbers, commonly denoted Fn, form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,
F0 = 0, F1 = 1
Fn = Fn-1 + Fn-2 for n > 1.
The beginning of the sequence is thus: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ...
Mui Goku wrote:The return value indicates the indices of the Fibonacci series, for example, if you pass 5 as the value it will return 5 as at index 5 the value is 5, and for value 6 it will return 8
Thanks that clears my question. This means that the input 'n' represents the index of the series. I hope adding loggers clears your original doubt.
If I remember correctly, Fibonacci himself started from 1. He was trying to work out how many rabbits a field would contain if he started with one rabbit (well, more precisely one pair: one buck and one doe).