Sum All Odd Fibonacci Numbers - failing larger testcases

Sum All Odd Fibonacci Numbers - failing larger testcases
0

#1

The larger numbers don’t appear to be working, i.e. `sumFibs(1000)`. I can’t tell where my logic is going wrong. It works fine for smaller numbers.

``````
function sumFibs(num) {
//Build array of fib sequence below num; incl num
let fibarr = [1,1];

for(var i = 2; i < num; i++){
let newfibseq = fibarr[i-1] + fibarr[i-2];
fibarr.push(newfibseq);
}

//Go through the list and find all odd numbers

let newfibarr = [];

for(var j = 0; j < fibarr.length; j++){
if(fibarr[j] % 2 !== 0){
newfibarr.push(fibarr[j]);
}
}

//Add all those odd numbers together

return newfibarr.reduce((accumulator, currentValue) => accumulator + currentValue );

}

// sumFibs(4);

``````

#2

I think you are supposed to get the sum of all fibonacci numbers in the fibonacci sequence that are lower than the num parameter, not the sum of all the fibonacci numbers lower than the num-th element in the sequence.

#3

As @RadoIIvanov has said, you aren’t summing the first `num` odd fibonacci numbers, you’re summing the odd Fibonacci numbers that are equal to or lower than `num`.

So, the logic:

1. Start with an initial array, an array index, and a zero-value return variable.
2. While the last member of that array is less than `num`, stick a new element on the end of the array, equal to the sum of the last two. Keep doing this step.
3. Iterate over the given array and, if the current member is odd, add that value to our return variable. Note: that is not append it to an Array, but add it to an actual accumulating value.
4. Return that sucker!

#4

This answer helped me solve it, after over 24 hours struggling with this algorithm. Thanks for the tips, @snowmonkey!

#5

Glad it worked out, @ChiselD. Love it when folks read past posts, the answers to a great many common questions are hidden in them!

Best of luck.