Problem
Begin the sequence with 1 and 2. Each following term is the sum of the previous two. Include only even-valued terms no greater than limit, then add them.
Implement even_fibonacci_sum(limit).
Input
limit: The largest term value that may be included.
Output
Return the sum, or 0 if there are no eligible terms.
Constraints
0 ≤ limit ≤ 10¹⁵. The result fits a signed 64-bit integer.
Examples
Input:
limit = 50
Expected output:
expected = 44
Input:
long long limit = 50;
Expected output:
long long expected = 44;
Input:
long limit = 50;
Expected output:
long expected = 44;
Explanation
The even terms are 2, 8, and 34. Their sum is 44.
Input:
limit = 1
Expected output:
expected = 0
Input:
long long limit = 1;
Expected output:
long long expected = 0;
Input:
long limit = 1;
Expected output:
long expected = 0;
Explanation
The first even term is 2, which exceeds the limit.
How to approach it
Try on your own first, then open one hint at a time.
Hint 1
You only need the even Fibonacci terms, not the entire sequence.
Hint 2
Generate the sequence until the next term exceeds the limit and add qualifying terms.
Hint 3
Watch the boundary when the limit itself is a Fibonacci term.
Expected complexity
O(log limit) time, O(1) extra space
References
This challenge is adapted for CodeUtility. Follow the statement and constraints above.