“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 or equal to 10 are 1, 1, 3, and 5.
Remember to use Read-Search-Ask if you get stuck. Try to pair program. Write your own code.”
So, I came up with a rather long solution for 5 out of the 6 tests but I cannot make it work when the test runs with a value of 4.000.000.
I could just look it up and use somebody else’s code but now I wonder why mine doesn’t work for 4.000.000 in particular!
Here is my code:
function sumFibs(num) {
let fullArray = [];
let fibonacciArray = [0, 1, 1];
let oddFibonacci = [];
let fCounter = 2;
let summed;
for (let i = 1; i <= num; i++) {
fullArray.push(i);
}
for (let j = 1; j <= fullArray.length; j++) {
if (fullArray[j] === fibonacciArray[fCounter] + fibonacciArray[fCounter - 1]) {
fibonacciArray.push(fullArray[j])
fCounter ++;
}
}
oddFibonacci = fibonacciArray.filter((el) => {
return el % 2 != 0;
});
summed = oddFibonacci.reduce((accumulator, currentValue) => accumulator + currentValue);
console.log(summed)
}
sumFibs(4000000);
Thank you in advance.