I\'m trying to create a function to calculate the sum of only even numbers in Fibonacci sequence. How can I make this if/while loop to work?.
function fib() {
Replace while(x % 2)
with while(x % 2 === 0)
. You're checking if x % 2
is true in your original while loop.
function sumFibs(num) {
let a = 1,
b = 1,
acc = 0;
for (let i = 0; i < num - 2; i++) {
let c = a;
a += b;
b = c;
if (a % 2 === 0) {
acc += a;
}
}
return acc;
}
console.log(sumFibs(10)); // Logs out the even sum of the first 10 fabonacci sequence