Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

239
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda