Facile 0 résolus 0 % de réussite

Tribonacci

Return the nth tribonacci number, where each term is the sum of the three before it.

Ce que vous allez apprendre

  • Compute a sequence iteratively
  • Keep only the last few terms
  • Handle the starting terms directly

Problème

Afficher la traduction

The tribonacci numbers extend the Fibonacci idea to three terms: T(0) = 0, T(1) = 0, T(2) = 1, and from then on T(n) = T(n − 1) + T(n − 2) + T(n − 3). The sequence goes 0, 0, 1, 1, 2, 4, 7, 13, 24, 44, …

Implement tribonacci(n).

Input

n: The index of the term, starting at 0.

Output

Return T(n). Only the last three terms are needed at any time, so a loop with three variables is enough.

Contraintes

0 ≤ n ≤ 74

Exemples

Exemple 1
Entrée :
n = 7

Sortie attendue :
expected = 13
Entrée :
long long n = 7;

Sortie attendue :
long long expected = 13;
Entrée :
long n = 7;

Sortie attendue :
long expected = 13;

Explication

The terms are 0, 0, 1, 1, 2, 4, 7, 13, so T(7) = 13.

Exemple 2
Entrée :
n = 2

Sortie attendue :
expected = 1
Entrée :
long long n = 2;

Sortie attendue :
long long expected = 1;
Entrée :
long n = 2;

Sortie attendue :
long expected = 1;

Explication

T(2) is the first 1 in the sequence: 1.

Comment l'aborder

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

Indice 1

Return the first three terms directly.

Indice 2

Keep three variables and shift them along each step.

Indice 3

A recursive solution without memory repeats work and is far too slow.

Complexité attendue

O(n) time, O(1) extra space

Références

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

La meilleure solution validée de chaque codeur. Les plus rapides, les plus légères et les mieux notées passent devant.

Aucune solution validée pour l'instant. Résolvez-le et prenez la première place.

Apprenez des autres

Solutions de la communauté

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