Duplicate of the last two fibonacci
I am trying to print Fibonacci numbers up to n. The code below prints the last number twice for whatever reason, please help.
function fibonacci(n) {
let i;
const fib = [];
fib[0] = 0;
fib[1] = 1;
for (i=2; i<n; i++) {
fib[i] = fib[i-2] + fib[i-1];
fib.push(fib[i]);
}
console.log( fib );
}
source to share
You need to assign either the value in the index or push the amount.
function fibonacci(n) {
let i;
const fib = [];
fib[0] = 0;
fib[1] = 1;
for (i = 2; i < n; i++) {
fib[i] = fib[i - 2] + fib[i - 1]; // either this assignm. or the next line only
// fib.push(fib[i - 2] + fib[i - 1]);
}
return fib;
}
console.log(fibonacci(8));
source to share
Just remove
fib.push(fib[i]);
Then
function fibonacci(n) {
let i;
const fib = [];
fib[0] = 0;
fib[1] = 1;
for (i=2; i<n; i++) {
fib[i] = fib[i-2] + fib[i-1];
}
}
fibonacci(7);
will give the result:
[ 0, 1, 1, 2, 3, 5, 8 ]
Update
Following the comment, I have committed the code to make it possible to use it for i=1
"use strict";
function fibonacci(n) {
let i;
const fib = [];
fib[0] = 0;
for (i=1; i<n; i++) {
fib[i] = ((fib[i-2]!==undefined)?fib[i-2]:1) + fib[i-1];
}
console.log(fib)
}
fibonacci(1);
fibonacci(2);
fibonacci(7);
[ 0 ]
[ 0, 1 ]
[ 0, 1, 1, 2, 3, 5, 8 ]
I removed the definition fib[1]
and in sum, using the i
element use value 1
for them only when fib[i-2]
equals undefinted
, this means that this condition is only met when i=1
, because the loop starts from 1
, but the table fib
has no key -1
. When i
greater than 1
, then exists fib[i-2]
and the equation has the same meaning as before.
source to share
You are doing it wrong: first you create the nth element in the array, and then you push the same element in the array, duplicating it. You don't need a push command.
Correct code:
function fibonacci(n) {
let i;
const fib = [];
fib[0] = 0;
fib[1] = 1;
for (i=2; i<n; i++) {
fib[i] = fib[i-2] + fib[i-1];
}
console.log( fib );
}
fibonacci(5);
source to share