Fácil 0 resueltos 0% de aceptación

Tribonacci

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

Lo que aprenderás

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

Problema

Ver traducción

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.

Restricciones

0 ≤ n ≤ 74

Ejemplos

Ejemplo 1
Entrada:
n = 7

Salida esperada:
expected = 13
Entrada:
long long n = 7;

Salida esperada:
long long expected = 13;
Entrada:
long n = 7;

Salida esperada:
long expected = 13;

Explicación

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

Ejemplo 2
Entrada:
n = 2

Salida esperada:
expected = 1
Entrada:
long long n = 2;

Salida esperada:
long long expected = 1;
Entrada:
long n = 2;

Salida esperada:
long expected = 1;

Explicación

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

Cómo abordarlo

Inténtalo primero por tu cuenta y luego abre las pistas una a una.

Pista 1

Return the first three terms directly.

Pista 2

Keep three variables and shift them along each step.

Pista 3

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

Complejidad esperada

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

Referencias

Este reto está adaptado para CodeUtility. Sigue el enunciado y las restricciones indicadas arriba.

Clasificación

Clasificación completa

La mejor solución aprobada de cada programador. Las más rápidas, ligeras y mejor valoradas van primero.

Aún no hay soluciones aprobadas. Resuélvelo y quédate el primer puesto.

Aprende de otros

Soluciones de la comunidad

Aún no hay soluciones publicadas. Resuelve este reto para compartir la primera.