9

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]

Tom O.
  • 5,730
  • 2
  • 21
  • 35
sumon
  • 147
  • 1
  • 1
  • 5

16 Answers16

9

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.

Saif
  • 2,530
  • 3
  • 27
  • 45
5

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),
        []
      )
mojtaba ramezani
  • 1,461
  • 16
  • 15
2

This function is incorrect. It cat be checked by just adding the console.log call just before the function return:

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);
  }
  console.log(result);
  return result[n];

}

console.log(fib(7));

As you can see, the sequence is wrong and (for n = 7) the return value is too.

The possible change would be as following:

function fib(n) {

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

}

console.log(fib(8));

This is the "classical" Fibonacci numbers; if you really want to use the first number of 0, not 1, then you should return result[n-1], since array indexes start from zero.

Cerberus
  • 8,879
  • 1
  • 25
  • 40
2

One approach you could take for fibonacci sequence is recursion:

var fibonacci = {
  getSequenceNumber: function(n) {
    //base case to end recursive calls
    if (n === 0 || n === 1) {
      return this.cache[n];
    }

    //if we already have it in the cache, use it
    if (this.cache[n]) {
      return this.cache[n];
    }
    //calculate and store in the cache for future use
    else {
      //since the function calls itself it's called 'recursive'
      this.cache[n] = this.getSequenceNumber(n - 2) + this.getSequenceNumber(n - 1);
    }

    return this.cache[n];
  },

  cache: {
    0: 0,
    1: 1
  }
}
//find the 7th number in the fibbonacci function
console.log(fibonacci.getSequenceNumber(7));

//see all the values we cached (preventing extra work)
console.log(fibonacci.cache);

//if you want to output the entire sequence as an array:
console.log(Object.values(fibonacci.cache));

The code above is also an example of a dynamic programming approach. You can see that I am storing each result in a cache object the first time it is calculated by the getSequenceNumber method. This way, the second time that getSequenceNumber is asked to find a given input, it doesn't have to do any actual work - just grab the value from cache and return it! This is an optimization technique that can be applied to functions like this where you may have to find the value of a particular input multiple times.

Tom O.
  • 5,730
  • 2
  • 21
  • 35
1

const fib = n => {
  const array = Array(n);
  for (i = 0; i < array.length; i++) {
    if (i > 1) {
      array[i] = array[i - 1] + array[i - 2];
    } else {
      array[i] = 1;
    }
  }
  return array;
}

console.log(fib(5))
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
0

What you are doing wrong is adding the iterator index (i), whereas what you need to do is add the element in the result at that index.

function fib(n) {

  const result = [0, 1];

  for (let i = 2; i <= n; i++) {
    const a = result[(i - 1)];
    const b = result[(i - 2)];
    result.push(a + b);
  }
  console.log("Result Array: " + result);
  return result[n];

}

console.log("Fibonacci Series element at 8: " + fib(8));
code
  • 2,115
  • 1
  • 22
  • 46
0

There are two issues with the logic:

  1. Variables a and b currently refer to i - 1 and i - 2. Instead they should refer to the elements of result array, i.e. result[i - 1] and result[i - 2].

  2. If you need 8th element of the array, you need to call result[7]. So the returned value should be result[n - 1] instead of result[n].

function fib(n) {

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

console.log(fib(8));
Nisarg Shah
  • 14,151
  • 6
  • 34
  • 55
0

simple solution for Fibonacci series:

function fib(n){
    var arr = [];
    for(var i = 0; i <n; i++ ){
        if(i == 0 || i == 1){
            arr.push(i);
        } else {
            var a = arr[i - 1];
            var b = arr[i - 2];
            arr.push(a + b);
        }
    }
    return arr
}
console.log(fib(8))
patki
  • 33
  • 6
0

This is certainly one of those "more than one way to clean chicken" type situations, this JavaScript method below works for me.

function fibCalc(n) {
    var myArr = [];

    for (var i = 0; i < n; i++) {
        if(i < 2) {
            myArr.push(i);
        } else {
            myArr.push(myArr[i-2] + myArr[i-1]);
        }
    } 

    return myArr;
}

fibCalc(8);

When called as above, this produces [0,1,1,2,3,5,8,13] It allows me to have a sequence of fib numbers based on n.

Boyan Hristov
  • 1,067
  • 3
  • 15
  • 41
ShawnTG71
  • 1
  • 2
0
function fib(n) {
    const result = [0];

    if (n > 1) {
        result.push(1);

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

    }
    console.log(result);
}
AYO O.
  • 99
  • 1
  • 1
0

i came up with this solution to get the n index fibonacci value.

function findFac(n){
if (n===1) 
  {
   return [0, 1];
  } 
  else 
  {
    var s = findFac(n - 1);
    s.push(s[s.length - 1] + s[s.length - 2]);
    return s;
  }
}

function findFac0(n){
var vv1 = findFac(n);
return vv1[n-1];
}


console.log(findFac0(10));
Viraj
  • 638
  • 1
  • 8
  • 10
0

Here, you have it, with few argument check, without using exception handling

function fibonacci(limit){
    if(typeof limit != "number"){return "Please enter a natural number";}

    if(limit <=0){
        return "limit should be at least 1";
    }
    else if(limit == 1){
        return [0];
    }
    else{
        var series = [0, 1];
        for(var num=1; num<=limit-2; num++){
            series.push(series[series.length-1]+series[series.length-2]);
        }
        return series;
    }
}
Kiran Racherla
  • 219
  • 3
  • 12
0

I came up with this solution.

function fibonacci(n) {
    if (n == 0) {
        return [0];
    }
    if ( n == 1) {
        return [0, 1];
    } else {
        let fibo = fibonacci(n-1);
        let nextElement = fibo [n-1] + fibo [n-2];
        fibo.push(nextElement);
        return fibo;
    }
}
console.log(fibonacci(10));
Aziza Kasenova
  • 1,501
  • 2
  • 10
  • 22
0
function fibonacciGenerator (n) {
 var output = [];
  if(n===1){
    output=[0];
  }else if(n===2){
    output=[0,1];    
  }else{
    output=[0,1];
    for(var i=2; i<n; i++){
      output.push(output[output.length-2] + output[output.length-1]);
    }
  }
  return output;
}
output = fibonacciGenerator();
console.log(output);
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 02 '22 at 16:27
  • Answer could do with some amount of explanation, especially to stand out from the other 13 answers – Zach Jensz Jun 04 '22 at 13:45
0
function fibonacci(end) {
    if (isNaN(end) === false && typeof (end) === "number") {
        var one = 0, res, two = 1;
        for (var i = 0; i < end; ++i) {
            res = one + two;
            one = two;
            two = res;
            console.log(res);
        }
    } else {
        console.error("One of the parameters is not correct!")
    }
}

fibonacci(5);
0
     var input = parseInt(prompt(""));
     var a =0;
     var b=1;
     var x;
     for(i=0;i<=input;i++){
        document.write(a+"<br>")
        x = a+b;
        a =b;
        b= x;
     }