Back to challenges
Easy 0 solved 0% acceptance

Sum Even Fibonacci Terms

Add the even Fibonacci terms that do not exceed a limit.

What you'll learn

  • Generate Fibonacci terms up to a limit
  • Keep only the even terms
  • Stop the loop at the right moment

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

Example 1
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.

Example 2
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.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.