2

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.

3
  • 1
    This is a recursive solution. Commented Apr 26, 2022 at 18:44
  • (n-1)+(n-2) is the same as n-1+n-2 is the same as n+n-1-2 is the same as 2*n-3. Simply an arithmetic expression whose value is calculated and returned. fibonacci(n-1) and fibonacci(n-2), on the other hand, are function calls. Commented Apr 26, 2022 at 18:52
  • I'm having trouble understand what the point of your question is. Are you just confused by the syntax? Or do you understand what 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 is log(n) not the same as n?" or "Why is x+5 not doing the same as x?", and I don't know how to answer that. Commented Apr 26, 2022 at 18:56

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.