DEV Community

Irene  Njuguna
Irene Njuguna

Posted on

Problem 2:

Question:

Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:

1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...

By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.

Solution

function sumEvenFibonacci(limit) {
let sum = 0;
let fibPrev = 1;
let fibCurr = 2;

while (fibCurr <= limit) {
if (fibCurr % 2 === 0) {
sum += fibCurr;
}
let fibNext = fibPrev + fibCurr;
fibPrev = fibCurr;
fibCurr = fibNext;
}

return sum;
}

Explanation

Define a function sumEvenFibonacci that takes a limit as an argument.initialize the variables sum to keep track of the sum, fibPrev to store the previous Fibonacci number, and fibCurr to store the current Fibonacci number.start the Fibonacci sequence with the initial values of 1 and 2.
Then use a while loop to generate Fibonacci numbers until the current Fibonacci number exceeds the given limit. Inside the loop, It checks the current Fibonacci number is even (fibCurr % 2 === 0). If it is, we add it to the sum.
Update the Fibonacci numbers by assigning fibCurr to fibPrev and fibNext (the sum of fibPrev and fibCurr) to fibCurr.
Return the sum.

Top comments (0)