G.T. - 4 months ago 36

Javascript Question

Challenge I'm working on:

**Sum All Odd Fibonacci Numbers**

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 10 are 1, 1, 3, and 5.

EX:

*sumFibs(1000) should return 1785.*

*sumFibs(4000000) should return 4613732.*

*sumFibs(4) should return 5.*

Here's what I have that works:

`function sumFibs(num) {`

if (num === 1) {return 1;}

var fibList = [1, 1];

for(i=2; i < num; i++){

if (fibList[i-1] + fibList[i-2] > num){

break;

}

//else if ((fibList[i-1] + fibList[i-2])%2 !== 0){

fibList.push(fibList[i-1] + fibList[i-2]);

//}

}

return fibList.reduce(function(a, b){return a+b;});

}

It gives me the sum of the Fibonacci sequence, even and odd, up to the value that is less than or equal to the inputted number.

However, part of the challenge was to only add up the odd numbers. Initially, I thought this would be easy enough, but my best efforts have all failed. The part of my code that doesn't work is commented out. Any input equal to 4 or higher yields "NaN" as the result.

Can anyone help? Thanks so much.

Answer

If you want to sum only the odd fibonacci numbers, then you can adjust the lambda you're using in `reduce`

to reflect that.

```
function sumFibs(num) {
if (num === 1) {return 1;}
var fibList = [1, 1];
for(i=2; i < num; i++){
if (fibList[i-1] + fibList[i-2] > num){
break;
}
fibList.push(fibList[i-1] + fibList[i-2]);
}
return fibList.reduce(function(a, b){
return a + b%2 * b;
});
}
```

The reason your commented code doesn't work is that in order to calculate fibonacci numbers in the first place, you must track *all* of them, not just the odd ones. For example, to get `5`

, you must calculate `2 + 3`

, which you can only do if you've recorded a `2`

in the first place.

The reason you're getting `NaN`

instead of some other wrong number, is that your loop expects `fibList[i - 1]`

to be filled with a real number. `i`

gets incremented every iteration, but the array doesn't always get a new element. In a sense, `i`

outruns the size of the array, so the addition operands aren't summing real numbers.