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]
result
orresult[n]
? – Subcutaneous