Problema
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.
Restrições
0 ≤ limit ≤ 10¹⁵. The result fits a signed 64-bit integer.
Exemplos
Entrada:
limit = 50
Saída esperada:
expected = 44
Entrada:
long long limit = 50;
Saída esperada:
long long expected = 44;
Entrada:
long limit = 50;
Saída esperada:
long expected = 44;
Explicação
The even terms are 2, 8, and 34. Their sum is 44.
Entrada:
limit = 1
Saída esperada:
expected = 0
Entrada:
long long limit = 1;
Saída esperada:
long long expected = 0;
Entrada:
long limit = 1;
Saída esperada:
long expected = 0;
Explicação
The first even term is 2, which exceeds the limit.
Como abordar
Tente sozinho primeiro e depois abra uma dica de cada vez.
Dica 1
You only need the even Fibonacci terms, not the entire sequence.
Dica 2
Generate the sequence until the next term exceeds the limit and add qualifying terms.
Dica 3
Watch the boundary when the limit itself is a Fibonacci term.
Complexidade esperada
O(log limit) time, O(1) extra space
Referências
Este desafio foi adaptado para o CodeUtility. Siga o enunciado e as restrições acima.