Even Fibonacci Numbers Sum - GeeksforGeeks
Given a limit, find the sum of all the even-valued terms in the Fibonacci sequence below given limit.
Read full article from Even Fibonacci Numbers Sum - GeeksforGeeks
Given a limit, find the sum of all the even-valued terms in the Fibonacci sequence below given limit.
The first few terms of Fibonacci Numbers are, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233 ,… (Even numbers are highlighted).
A simple solution is to iterate through all prime numbers while the next number is less than or equal to given limit. For every number, check if it is even. If the number is even, add it to the result.
An efficient solution is based on the below recursive formula for even Fibonacci Numbers
Recurrence for Even Fibonacci sequence is: EFn = 4EFn-1 + EFn-2 with seed values EF0 = 0 and EF1 = 2. EFn represents n'th term in Even Fibonacci sequence.
// Returns sum of even Fibonacci numbers which are
// less than or equal to given limit.
int
evenFibSum(
int
limit)
{
if
(limit < 2)
return
0;
// Initialize first two even prime numbers
// and their sum
long
long
int
ef1 = 0, ef2 = 2;
long
long
int
sum = ef1 + ef2;
// calculating sum of even Fibonacci value
while
(ef2 <= limit)
{
// get next even value of Fibonacci sequence
long
long
int
ef3 = 4*ef2 + ef1;
// If we go beyond limit, we break loop
if
(ef3 > limit)
break
;
// Move to next even number and update sum
ef1 = ef2;
ef2 = ef3;
sum += ef2;
}
return
sum;
}