Not sure where I'm going wrong

Tell us what’s happening:

I’m trying to do the assignment : given a positive integer num , return the sum of all odd Fibonacci numbers that are less than or equal to num .

The below code seems to be working for small values, but the tests on large values are failing. What’s happening?

Your code so far


function sumFibs(num) {

let arr = [1, 1];
let i = 0;

while(arr.length < num) {
  arr.push(arr[i] + arr[i+1]);
  i++;
}

let arrSum = arr.reduce(function(sum, val){
  if(val % 2 !== 0) {
    return sum + val;
  } else {
    return sum;
  }
});

return arrSum;
}

sumFibs(4);

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15.

Challenge: Sum All Odd Fibonacci Numbers

Link to the challenge:
https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-odd-fibonacci-numbers

what’s your check instead?

arr.length < num

think a bit about it.

2 Likes

Holy shit. I just realised I shouldn’t be so hasty in reading the problem statements! Thank you! On it! Will post the solution in a bit. :smiley:

@ilenia nice reply instead of revealing answer. I like it. :+1:

Got it! Thank you so much! :slight_smile:

function sumFibs(num) {

  let arr = [1, 1];
  let i = 0;

  while((arr[i] + arr[i+1]) <= num) {
    arr.push((arr[i] + arr[i+1]));
    i++;
  }

  let sumArr = arr.reduce(function(sum, val) {
    if(val % 2 != 0) {
      return sum + val;
    } else {
      return sum;
    }
  });

  return sumArr;
}

Okay! I posted since I thought if there’s a more optimal way of doing it, someone would point it out. But you have a point. I won’t post my solutions. :slight_smile: