Home > Blockchain >  problem with the logic behind Fibonacci nth term
problem with the logic behind Fibonacci nth term

Time:08-26

const fibonacci = function (n) {
  n = parseInt(n)
  if (n < 0) return 'OOPS'
  if (n < 2) return n
  else {
    return fibonacci(n - 1)   fibonacci(n - 2)
  }
}

this is a recursive function for solving the problem but I am finding it difficult to understand why the base case must evaluate to 1. I get the syntax but I don't get the logic behind the solution.

CodePudding user response:

The base case must evaluate to 1 because the first two terms of the Fibonacci sequence are 1, 1 (or in some cases 0, 1, which gives the same sequence starting with a zero).

Unrelated to your question, but the way you wrote that will be very slow because it will recalculate Fibonacci numbers lower than the target many, many times. If this must be recursive, then use memoization so each value is only calculated once.

CodePudding user response:

    var fibonacci_series = function (n) 
    {
      if (n===1) 
      {
        return [0, 1];
      } 
      else 
      {
        var s = fibonacci_series(n - 1);
        s.push(s[s.length - 1]   s[s.length - 2]);
        return s;
      }
    };
    
     console.log(fibonacci_series(8));

you can try this

  • Related