ง่าย 0 ข้อที่แก้แล้ว อัตราผ่าน 0%

Sum Even Fibonacci Terms

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

สิ่งที่คุณจะได้เรียนรู้

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

โจทย์

ดูฉบับแปล

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.

ตัวอย่าง

ตัวอย่างที่ 1
อินพุต:
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.

ตัวอย่างที่ 2
อินพุต:
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

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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก