Search code examples
javascriptalgorithmfunctiondata-structurescomputer-science

Difference between returning calculation with function name and without


The below function calculates the Fibonacci, why the last calculation needs to include the function name and not just (n-1)+(n-2) ?

function fibonacci(n){
    if (n===1){ return 1}
    else if (n===0){ return 0} 
    else return fibonacci(n-1)+fibonacci(n-2) // (n-1)+(n-2) does not work. Why?
}

I know this is a beginner question but couldn't find the answer. I'd appreciate any comments. I understand that I need to use recursion, but that's not the point of my question.


Solution

  • this is recursive solution:

    function fibonacci(n){
        if (n===1){ return 1}
        else if (n===0){ return 0} 
        else return fibonacci(n-1)+fibonacci(n-2) 
    }
    

    You are calling this function for nth fibonacci. But you don't know nth fibonacci yet. so you must find (n-1) and (n-2) fibonacci. That is why you must call fibonacci(n-1)+fibonacci(n-2). And you don't even know n-1th and n-2th fibonacci that is why you must call it until known fibonacci. You know first and second fibonaccis. That is wht when n == 1 or n==0 you return just answer.

    for example:

    n = 7
    
    fibonacci(7) = fibonacci(6) + fibonacci(5)
    fibonacci(6) = fibonacci(5) + fibonacci(4)
    fibonacci(5) = fibonacci(4) + fibonacci(3)
    fibonacci(4) = fibonacci(3) + fibonacci(2)
    fibonacci(3) = fibonacci(2) + fibonacci(1)
    fibonacci(2) = fibonacci(1) + fibonacci(0)
    fibonacci(1) = 1
    fibonacci(0) = 0