Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

304
Visualizações
Fibonacci sequence generator not working for 1 or 2 as inputs but it works for the rest of the sequence?

Can someone explain to me why my fibonacciGenerator function doesn't work with this code? I understand why it works with the second code tho but I just don't get why the first one doesn't.

function fibonacciGenerator(n) {

  if (n > 0) {
    var fArray = [];
    fArray.push(0);

    if (n >= 2) {
      fArray.push(1);
    }
    for (var i = 0; i < n; i++) {
      fArray.push(fArray[i] + fArray[i + 1]);
    }
    console.log(fArray);
  }
}

fibonacciGenerator(1);
fibonacciGenerator(2);

Second code working :

function fibonacciGenerator(n) {

  if (n > 0) {
    var fArray = [];
    fArray.push(0);

    if (n >= 2) {
      fArray.push(1);
    }
    for (var i = 2; i < n; i++) {
      fArray.push(fArray[i - 1] + fArray[i - 2]);
    }
    console.log(fArray);
  }
}

fibonacciGenerator(1);
fibonacciGenerator(2);

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

The first code is printing 2 extra Fibonacci number this is because:

you are first pushing 0 and 1 into the array as:

var fArray = [];
    fArray.push(0);
  
    if (n >=2 ){
        fArray.push(1);
    }

and then you loop over again till n times. Because of this reason it prints two extra Fibonacci numbers.

the solution is to either loop over n-2 time or to use the second code.

about 4 years ago · Juan Pablo Isaza Relatório

0

var fArray = [];
fArray.push(0);

if (n >= 2) {
  fArray.push(1);
}

The initial condition is to cover n=1: [0] and n=2: [0,1]

The 2nd code is working because the loop only starts when n is greater than i, so means it skips the loop with n < 2.

For your problem, you don't skip the loop when n < 2.

for (var i = 0; i < n; i++) {
  fArray.push(fArray[i] + fArray[i + 1]);
}

You can imagine the result will be like below when n < 2 with your loop. Note that the inital value is fArray = [0]

fArray.push(fArray[0] + fArray[1]); //fArray[1] is undefined because you only have 1 item in your array

In this case fArray[0] + fArray[1] ==> 0 + undefined = NaN

So that's why your logic does not work when n < 2

To correct it, you need to avoid the loop if n < 2

//if n=1 or n=2, it won't trigger the loop due to `i < n-2`
for (var i = 0; i < n-2; i++) {
   fArray.push(fArray[i] + fArray[i + 1]);
}
about 4 years ago · Juan Pablo Isaza Relatório

0

The idea to have i start with 0 instead of 2, and to adjust the body of the loop accordingly, is fine, but there is one thing that the first version didn't adjust: the stop condition of the loop.

By setting i=0, the first version loops 2 times more than the second version. You should also alter the end condition in the same way: instead of i < n, it should have i < n - 2, so to ensure the number of iterations is the same as in the second version.

Not related to your question, but the console.log should better be placed outside of the function. The job of the function should be to return the array, not to print it. So also, when n > 0 is false, it should return an empty array.

function fibonacciGenerator(n) {

  var fArray = [];
  if (n > 0) {
    fArray.push(0);

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

console.log(fibonacciGenerator(1));
console.log(fibonacciGenerator(2));

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda