I am working on a function that shows the value of a given number in the Fibonacci sequence. However, it seems the last number is not quite correct on following the Fibonacci algorithm. Any clues on what I am doing wrong here?
const fibonacci = function(num) {
let fsec=[];
fsec[0]= 0;
fsec[1]= 1;
for(let i=2; i<=num; i++){
fsec[i]=fsec[i-2]+fsec[i-1];
fsec.push(i)
}
return fsec[fsec.length-1]
};
fibonacci(6)
2 things in your for loop. i should be less than num and the push should push the number, not the iterator.
Change to this:
for(let i=2; i<num; i++){
fsec[i]=fsec[i-2]+fsec[i-1];
fsec.push(fsec[i])
}
use below code:
const fibonacci = function(num) {
let fsec=[];
fsec[0]= 0;
fsec[1]= 1;
for(let i=2; i<num; i++){
fsec.push(fsec[i-2]+fsec[i-1])
}
// console.log(fsec)
// console.log(fsec[fsec.length-1])
return fsec[fsec.length-1]
};
fibonacci(6)
The fsec.push(i) is unnecessary and is the problem in this case..
const fibonacci = function(num) {
let fsec=[];
fsec[0]= 0;
fsec[1]= 1;
for(let i = 2; i <= num; i++){
fsec[i] = fsec[i-2] + fsec[i-1];
}
return fsec[fsec.length - 1]
};
console.log(fibonacci(6));