Having problem to understand [Sum All Odd Fibonacci Numbers]

Here is the problem is known as Sum All Odd Fibonacci Numbers.
I have a problem with a test case.

sumFibs(10) should return 10 because all odd Fibonacci numbers less than or equal to 10 are 1, 1, 3, and 5.

But why,

sumFibs(4) should return 5 ?
All odd Fibonacci numbers less than or equal to 4 are just 1 and 1.
So here, my expectation is sumFibs(4) should return 2 but it’s saying 5.
Can you please help me to figure out what’s going on?

1, 1, and 3 are all less than 4.

1 Like

Here is my code.

function sumFibs(num) {
  var res = [];
    var one = 0;
    var two = 1;
    var temp;
    for(let i=0; i<num; i++){
      if(one<num){
        res.push(one);
        temp = one;
      }
      one = two;
      two = temp + one
    }
    console.log(res);
    res = res.filter(x => x%2 !== 0);
    console.log(res)
  return res.reduce((a,b) => a+b,0);
}

First, I generate all Fibonacci numbers using a loop num times. It’s the wrong way right?

i <= num improve me but still,
I’m getting

sumFibs(75025)  return 60696.

instead of

sumFibs(75025) return 135721.

Ah, you need the individual Fibonacci numbers to be less than or equal to num. You don’t want the first num Fibonacci numbers.


Once you get it working, I’d recommend refactoring this code to sum the numbers as you generate them instead of keeping an array of the numbers. Makng and summing that array seriously slows down your code.

1 Like
i <= num
//then inside loop
one <= num

fixed my issue. Let’s refactor this~

1 Like

@JeremyLT
It’s more faster right :relaxed: :partying_face:

function sumFibs(num) {
    var sum = 0;
    var one = 0;
    var two = 1;
    var temp;
    for(let i=0; i<=num; i++){
      if(one<=num){
        if(one%2 !== 0){
          sum += one
        }
        temp = one;
      }
      one = two;
      two = temp + one;
    }
  return sum;
}
1 Like

Nice!

Its one of those funny things that people don’t always realize - arrays are really expensive to build one element at a time

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.