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?
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?
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.
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;
}