Fibonacci's test does nt make sense

Tell us what’s happening:
Given a positive integer num , return the sum of all odd Fibonacci numbers that are less than or equal to num .
Dont get why the tests request, if that value will be greater than num:

sumFibs(1000) should return 1785.

sumFibs(75025) should return 135721.


**Your code so far**
      
```js

function sumFibs(num) {  
const f=[1];
for(let i=0;i<num-1;i++){
      if(i<=0){
        f.push(1);
      }else{
        if(f.reduce(function (sum, curr) {return sum + curr;})<=num){
        f.push(f[i]+f[i-1]);
      }  
  }
}
return f.filter(a=>a%2!==0).reduce(function (sum, curr) {return sum + curr;});
}

sumFibs(10);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.102 Safari/537.36.

Challenge: Sum All Odd Fibonacci Numbers

Link to the challenge:

Hello and welcome to the freeCodeCamp community~!

Could you provide a little more clarification?

I am not passing the test sumFibs(75024) should return 60696 for https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/sum-all-odd-fibonacci-numbers

My code is the following:

function sumFibs(num) {  
  const f=[1];
  for(let i=0;i<num;i++){
        if(i<=0){
          f.push(1);
        }else{
          if(f.filter(a=>a%2!==0).reduce(function (sum, curr) {return sum + curr;})<num){
          f.push(f[i]+f[i-1]);
        }  
    }
}
return f.filter(a=>a%2!==0).reduce(function (sum, curr) {return sum + curr;});
}

console.log(sumFibs(75024));


I solved it as follows but wanted to know why the other solution failed.:

function sumFibs(num) {
  var pNum = 0;
  var cNum = 1;
  var res = 0;
  while (cNum <= num) {
    if (cNum % 2 !== 0) {res += cNum;}
    cNum += pNum;
    pNum = cNum-pNum;
  }
  return res;
}

Your issue is here. You are making up to the num-1th Fibonacci number. You need up to make the Fibonacci number that does not exceed num.

i.e.

f_0 = 0
f_1 = 1
f_2 = 2
f_3 = 3
f_4 = 5
f_5 = 8
f_6 = 13

f_6 is the 6th Fibonacci number but its value is 13. You need the values to not exceed num.

Your second approach is better anyways.

The two rules of fast/efficient/maintainable code are

  1. Never store a value you only use once

  2. Never do unnecessary calculations

In this case, you only need to sum values once, so you will get faster code if you don’t store the full Fibonacci sequence.

1 Like