Torna alle sfide
Facile 0 risolte 0% di accettazione

Fibonacci Number

Return the n-th Fibonacci number.

Cosa imparerai

  • Generate a sequence from its previous terms
  • Update two variables at once
  • See why naive recursion is slow

Problema

Mostra traduzione

The Fibonacci sequence starts 0, 1 and each next number is the sum of the previous two: 0, 1, 1, 2, 3, 5, 8, …. F(0) = 0 and F(1) = 1.

Implement fibonacci(n).

Input

n: The position in the sequence.

Output

Return F(n).

Vincoli

0 ≤ n ≤ 90

Esempi

Esempio 1
Input:
n = 10

Output atteso:
expected = 55
Input:
long long n = 10;

Output atteso:
long long expected = 55;
Input:
long n = 10;

Output atteso:
long expected = 55;

Spiegazione

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55: F(10) = 55.

Esempio 2
Input:
n = 0

Output atteso:
expected = 0
Input:
long long n = 0;

Output atteso:
long long expected = 0;
Input:
long n = 0;

Output atteso:
long expected = 0;

Spiegazione

By definition F(0) = 0.

Come affrontarlo

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

Suggerimento 1

The first two values are fixed, so start from the base cases.

Suggerimento 2

Build later values from the two previous ones instead of recomputing recursively.

Suggerimento 3

Use an iterative approach to avoid repeated work and deep recursion.

Complessità attesa

O(n) 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.