Torna alle sfide
Facile 0 risolte 0% di accettazione

Sum Even Fibonacci Terms

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

Cosa imparerai

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

Problema

Mostra traduzione

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.

Vincoli

0 ≤ limit ≤ 10¹⁵. The result fits a signed 64-bit integer.

Esempi

Esempio 1
Input:
limit = 50

Output atteso:
expected = 44
Input:
long long limit = 50;

Output atteso:
long long expected = 44;
Input:
long limit = 50;

Output atteso:
long expected = 44;

Spiegazione

The even terms are 2, 8, and 34. Their sum is 44.

Esempio 2
Input:
limit = 1

Output atteso:
expected = 0
Input:
long long limit = 1;

Output atteso:
long long expected = 0;
Input:
long limit = 1;

Output atteso:
long expected = 0;

Spiegazione

The first even term is 2, which exceeds the limit.

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

You only need the even Fibonacci terms, not the entire sequence.

Suggerimento 2

Generate the sequence until the next term exceeds the limit and add qualifying terms.

Suggerimento 3

Watch the boundary when the limit itself is a Fibonacci term.

Complessità attesa

O(log limit) time, O(1) extra space

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.