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]
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),
[]
)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With