Retour aux défis
Facile 0 résolus 0 % de réussite

Sum Even Fibonacci Terms

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

Ce que vous allez apprendre

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

Problème

Afficher la traduction

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.

Contraintes

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

Exemples

Exemple 1
Entrée :
limit = 50

Sortie attendue :
expected = 44
Entrée :
long long limit = 50;

Sortie attendue :
long long expected = 44;
Entrée :
long limit = 50;

Sortie attendue :
long expected = 44;

Explication

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

Exemple 2
Entrée :
limit = 1

Sortie attendue :
expected = 0
Entrée :
long long limit = 1;

Sortie attendue :
long long expected = 0;
Entrée :
long limit = 1;

Sortie attendue :
long expected = 0;

Explication

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

Comment l'aborder

Essayez d'abord seul, puis ouvrez les indices un par un.

Indice 1

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

Indice 2

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

Indice 3

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

Complexité attendue

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

Références

Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.

Apprenez des autres

Solutions de la communauté

Aucune solution publiée pour l'instant. Résolvez ce défi pour partager la première.