Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fibonacci series in JavaScript

function fib(n) {

  const result = [0, 1];
  for (var i = 2; i <= n; i++) {
    const a = (i - 1);
    const b = (i - 2);
    result.push(a + b);
  }
  return result[n];

}

console.log(fib(8));

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]

like image 948
sumon Avatar asked Jun 30 '18 04:06

sumon


2 Answers

My solution for Fibonacci series:

 const fibonacci = n =>
      [...Array(n)].reduce(
        (acc, val, i) => acc.concat(i > 1 ? acc[i - 1] + acc[i - 2] : i),
        []
      )
like image 184
mojtaba ramezani Avatar answered Oct 16 '22 12:10

mojtaba ramezani


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.

like image 21
Saif Avatar answered Oct 16 '22 12:10

Saif