難しい 0件解決済み 正答率0%

Longest Recurring Cycle

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

このチャレンジで学べること

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

問題

翻訳を表示

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.

制約

2 ≤ limit ≤ 2000

例

例 1
入力:
limit = 8

期待される出力:
expected = 7
入力:
long long limit = 8;

期待される出力:
long long expected = 7;
入力:
long limit = 8;

期待される出力:
long expected = 7;

解説

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

例 2
入力:
limit = 5

期待される出力:
expected = 3
入力:
long long limit = 5;

期待される出力:
long long expected = 3;
入力:
long limit = 5;

期待される出力:
long expected = 3;

解説

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

解き方のヒント

まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。

ヒント 1

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

ヒント 2

Remember the step where each remainder first appeared.

ヒント 3

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

目安の計算量

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

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

まだ合格した解答はありません。解いて 1 位になりましょう。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。