And when I was asking about approaches to solving a problem using recursion, I was talking in general about ALL questions that could be solved by recursion. I understood this Fibonacci one and then wrote this code.
I am intrigued about how you all think when coming up with a recursion solution. Do you find the iterative solution and then try to make a recursive one?
That actually depends. Normally the 1st fibonacci number is considered to be 1 and the 0th is considered 0, then you would return n. But every so often, we use 0 based indexing, as in the fib[0] being the first term, in which case you would return 1 for both.
If you want to become better at recursion, don’t think about whether the function is correct. Assume your function is correct for the previous terms. Then try to prove that if the algorithm gives the correct answer for the other terms I’m calling, will my algorithm be correct here also.
Also check whether you may be calling the same function twice. In which case you should also keep a table storing all the values you already know.
Your current implementation is exponential in time. Since T(n)=T(n-1)+T(n-2), where T(n) denotes the time taken to find the nth fibonacci number. When n is sufficiently large, it’s takes O(x^n), where x^n=x^{n-1}+x^{n-2} which is equivalent to x^2=x+1, hence x\approx 1.6. If you remember the answers, your running time falls to O(n) since you are only computing the answer for each term once, and there are n terms.
Hope this helps.