Tutte le sfide
Facile 0 risolte 0% di accettazione

First Fibonacci With N Digits

Find the position of the first Fibonacci number that has n digits.

Cosa imparerai

  • Add two digit arrays
  • Generate Fibonacci terms without overflow
  • Stop at the first term that meets a condition

Problema

Mostra traduzione

The Fibonacci sequence starts F(1) = 1, F(2) = 1, and each next term is the sum of the two before it: 1, 1, 2, 3, 5, 8, 13, 21, ... Find where the sequence first reaches n decimal digits. The terms soon outgrow 64-bit integers, so add them as digit arrays if your language has no big integers.

Implement fibonacci_with_n_digits(n).

Input

n: The number of digits.

Output

Return the index i of the first term F(i) with at least n digits. For n = 1 the answer is 1.

Vincoli

1 ≤ n ≤ 1000

Esempi

Esempio 1
Input:
n = 2

Output atteso:
expected = 7
Input:
long long n = 2;

Output atteso:
long long expected = 7;
Input:
long n = 2;

Output atteso:
long expected = 7;

Spiegazione

F(6) = 8 has one digit and F(7) = 13 has two, so the answer is 7.

Esempio 2
Input:
n = 4

Output atteso:
expected = 17
Input:
long long n = 4;

Output atteso:
long long expected = 17;
Input:
long n = 4;

Output atteso:
long expected = 17;

Spiegazione

F(16) = 987 and F(17) = 1597, so the answer is 17.

Come affrontarlo

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

Suggerimento 1

Keep only the last two terms.

Suggerimento 2

Store each term as digits and add them with carries.

Suggerimento 3

Count the index as you go, starting from F(1) = 1.

Complessità attesa

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

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

Ancora nessuna soluzione superata. Risolvila e prendi il primo posto.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.