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

238
Visualizações
Unsure about syntax/methods. I believe my code should work but it does not

Prompt: Given a positive integer num, return the sum of all odd Fibonacci numbers that are less than or equal to num. The first two numbers in the Fibonacci sequence are 1 and 1. Every additional number in the sequence is the sum of the two previous numbers. The first six numbers of the Fibonacci sequence are 1, 1, 2, 3, 5 and 8. For example, sumFibs(10) should return 10 because all odd Fibonacci numbers less than or equal to 10 are 1, 1, 3, and 5.

The code I wrote for this is:

function sumFibs(num) {
  const arr = [1,1];
  let sum = 0;
  for(let i = 2; i <= num; i++){
    let queef = arr[i - 1] + arr[i - 2];
    arr.push(queef);
  }
  for(let j = 0; j < arr.length; j++){
    if(arr[j] % 2 != 0){
      sum += arr[j];
    }
  }
  return sum;
}

console.log(sumFibs(6));

but i get 23 when it should be 10, I'm not sure why this doesn't work because i feel this would work in java. I have also tried to do arr[i] == queef but that also does not work. I am missing something or should this work?

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

0

Welcome Bethany, enjoy your new coding journey. If you change line 4 in your code to:

for(let i = 2; i < num; i++){

it returns 10

about 4 years ago · Juan Pablo Isaza Relatório

0

I think your error relies in

for(let i = 2; i <= num; i++){

I believe you're generating an amount of numbers till num instead of the value itself. Try with something like this (I tried to keep your style):

function sumFibs(num) {
  if (num === 1) return 1;
    
  const arr = [1,1];
  let sum = 2;
  for(let i = 2; i <= num; i++){
    let queef = arr[i - 1] + arr[i - 2];
    arr.push(queef);

    if(arr[i] % 2 != 0 && queef < num){
        sum += arr[i];
    }
  }
  return sum;
}

console.log(sumFibs(6));
about 4 years ago · Juan Pablo Isaza Relatório

0

It should be < num in the first for loop. Since array indexes start from 0 and not 1, when you type <= 6 it makes an array with 7 numbers in it.

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