問題
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.
制約
0 ≤ limit ≤ 10¹⁵. The result fits a signed 64-bit integer.
例
入力:
limit = 50
期待される出力:
expected = 44
入力:
long long limit = 50;
期待される出力:
long long expected = 44;
入力:
long limit = 50;
期待される出力:
long expected = 44;
解説
The even terms are 2, 8, and 34. Their sum is 44.
入力:
limit = 1
期待される出力:
expected = 0
入力:
long long limit = 1;
期待される出力:
long long expected = 0;
入力:
long limit = 1;
期待される出力:
long expected = 0;
解説
The first even term is 2, which exceeds the limit.
解き方のヒント
まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。
ヒント 1
You only need the even Fibonacci terms, not the entire sequence.
ヒント 2
Generate the sequence until the next term exceeds the limit and add qualifying terms.
ヒント 3
Watch the boundary when the limit itself is a Fibonacci term.
目安の計算量
O(log limit) time, O(1) extra space
参考資料
この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。