Reputation: 21
So i am supposed to add all the odd Fibonacci Numbers and return the sum. Here is my code but i am not getting it right. Sorry i am new at this so help me out.
function sumFibs(num) {
let secpre=0
let pre=1
let current=0;
let arr=[pre]
let y=[]
let sum
for(let i=1;i<=num;i++){
if(num==1){return 1}
else if((secpre+pre)<num){
current=secpre+pre;
secpre=pre;
pre=current;
arr.push(current)
}
}
arr.map(x=>{if(x%2!==0){
return y.push(x)
}})
y.reduce((a,b)=>{ sum=0;
sum+=a+b;
return sum
})
console.log(y)
console.log(sum)
return sum
}
sumFibs(75025)
for the value of sumFibs(75025), it should be 135721 but i am getting 60696.
Upvotes: 2
Views: 372
Reputation: 61
You've had a nice idea, well done! Although, here is the solution for which I think is simpler to understand:
function sumFib(num) {
let odd_sum = 1;
let nums = [0, 1];
while (odd_sum < num) {
new_num = nums[nums.length - 2] + nums[nums.length - 1];
nums.push(new_num);
if (new_num % 2 == 1) odd_sum += new_num;
}
return odd_sum;
}
console.log(sumFib(75025));
Feel free to ask if you are confused with something.
Upvotes: 1