vendredi 28 octobre 2016

Else if statement seems rational to me but breaks code

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.

Aucun commentaire:

Enregistrer un commentaire