Home > Back-end >  Unsure about syntax/methods. I believe my code should work but it does not
Unsure about syntax/methods. I believe my code should work but it does not

Time:06-04

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?

CodePudding user response:

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));

CodePudding user response:

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

CodePudding user response:

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.

  • Related