Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

unsure about syntax/methods in javascript. 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, im not sure why this doesnt 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 somthing or should this work?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading