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.
(n-1)+(n-2)is the same asn-1+n-2is the same asn+n-1-2is the same as2*n-3. Simply an arithmetic expression whose value is calculated and returned.fibonacci(n-1)andfibonacci(n-2), on the other hand, are function calls.return (n-1)+(n-2)means, and wonder why it doesn't work? Can you explain why you thought it would work? As the question is written, it's a bit like asking "Why islog(n)not the same asn?" or "Why isx+5not doing the same asx?", and I don't know how to answer that.