Fibonacci series in JavaScript

sumon picture sumon · Jun 30, 2018 · Viewed 13.1k times · Source

The output of the code above is 13. I don't understand the for loop part. In very first iteration i = 2, but after second iteration i = 3 so a = 2 and b = 1 and third iteration i = 4 so a = 3, b = 2, and so on... If it's going on final sequence will be : [0, 1, 1, 3, 5, 7, 9, 11], which is incorrect. The correct sequence will be [0, 1, 1, 2, 3, 5, 8, 13]

Answer

Saif Ur Rahman picture Saif Ur Rahman · Jun 30, 2018

You were not using the previous two numbers that are already in the array to > generate the new fibonacci number to be inserted into the array.

https://www.mathsisfun.com/numbers/fibonacci-sequence.html

Here I have used the sum of result[i-2] and result[i-1] to generate the new fibonacci number and pushed it into the array.

Also to generate n number of terms you need the condition to be i < n and not i <= n.

function fib(n) {

  const result = [0, 1];
  for (var i = 2; i < n; i++) {
    result.push(result[i-2] + result[i-1]);
  }
  return result; // or result[n-1] if you want to get the nth term

}

console.log(fib(8)); 

Return result[n-1] if you want to get the nth term.