Tutte le sfide
Difficile 0 risolte 0% di accettazione

Longest Recurring Cycle

Find the d up to a limit whose fraction 1/d has the longest repeating decimal block.

Cosa imparerai

  • Simulate long division with remainders
  • Detect a repeat with a lookup table
  • Find a cycle length from first positions

Problema

Mostra traduzione

Some unit fractions end (1/4 = 0.25) and the rest repeat forever: 1/6 = 0.1666... repeats a block of 1 digit and 1/7 = 0.142857142857... a block of 6. Among d = 2, 3, ..., limit, find the d whose 1/d has the longest repeating block. Do the long division by hand in code: the digits start repeating as soon as a remainder comes back.

Implement longest_recurring_cycle(limit).

Input

limit: The largest denominator to try.

Output

Return the d with the longest repeating block. A fraction that ends has a block length of 0. If several d tie, return the smallest.

Vincoli

2 ≤ limit ≤ 2000

Esempi

Esempio 1
Input:
limit = 8

Output atteso:
expected = 7
Input:
long long limit = 8;

Output atteso:
long long expected = 7;
Input:
long limit = 8;

Output atteso:
long expected = 7;

Spiegazione

Block lengths for 2 to 8 are 0, 1, 0, 0, 1, 6, 0, so the answer is 7.

Esempio 2
Input:
limit = 5

Output atteso:
expected = 3
Input:
long long limit = 5;

Output atteso:
long long expected = 3;
Input:
long limit = 5;

Output atteso:
long expected = 3;

Spiegazione

1/3 repeats one digit, 1/2, 1/4 and 1/5 end, so the answer is 3.

Come affrontarlo

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

Suggerimento 1

Each new digit of 1/d comes from the remainder times 10.

Suggerimento 2

Remember the step where each remainder first appeared.

Suggerimento 3

If the remainder becomes 0 the decimal ends; otherwise the cycle length is the gap between two visits of the same remainder.

Complessità attesa

O(limit²) time, O(limit) 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.