Fácil 0 resolvidos 0% de aceitação

Tribonacci

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

O que você vai aprender

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

Problema

Ver tradução

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.

Restrições

0 ≤ n ≤ 74

Exemplos

Exemplo 1
Entrada:
n = 7

Saída esperada:
expected = 13
Entrada:
long long n = 7;

Saída esperada:
long long expected = 13;
Entrada:
long n = 7;

Saída esperada:
long expected = 13;

Explicação

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

Exemplo 2
Entrada:
n = 2

Saída esperada:
expected = 1
Entrada:
long long n = 2;

Saída esperada:
long long expected = 1;
Entrada:
long n = 2;

Saída esperada:
long expected = 1;

Explicação

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

Como abordar

Tente sozinho primeiro e depois abra uma dica de cada vez.

Dica 1

Return the first three terms directly.

Dica 2

Keep three variables and shift them along each step.

Dica 3

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

Complexidade esperada

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

Referências

Este desafio foi adaptado para o CodeUtility. Siga o enunciado e as restrições acima.

A melhor solução aprovada de cada programador. As mais rápidas, leves e mais bem avaliadas ficam no topo.

Ainda não há soluções aprovadas. Resolva e fique com o primeiro lugar.

Aprenda com outros

Soluções da comunidade

Ainda não há soluções publicadas. Resolva este desafio para compartilhar a primeira.