Todos os desafios
Difícil 0 resolvidos 0% de aceitação

Longest Recurring Cycle

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

O que você vai aprender

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

Problema

Ver tradução

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.

Restrições

2 ≤ limit ≤ 2000

Exemplos

Exemplo 1
Entrada:
limit = 8

Saída esperada:
expected = 7
Entrada:
long long limit = 8;

Saída esperada:
long long expected = 7;
Entrada:
long limit = 8;

Saída esperada:
long expected = 7;

Explicação

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

Exemplo 2
Entrada:
limit = 5

Saída esperada:
expected = 3
Entrada:
long long limit = 5;

Saída esperada:
long long expected = 3;
Entrada:
long limit = 5;

Saída esperada:
long expected = 3;

Explicação

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

Como abordar

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

Dica 1

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

Dica 2

Remember the step where each remainder first appeared.

Dica 3

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

Complexidade esperada

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