中級 0件解決済み 正答率0%

Longest Collatz Chain

Find the starting number up to a limit whose Collatz chain is longest.

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

  • Generate a Collatz chain
  • Cache results to avoid repeated work
  • Break ties by the smallest value

問題

翻訳を表示

From any positive n, the Collatz rule makes the next term n / 2 when n is even and 3n + 1 when n is odd, and the chain stops when it reaches 1. The chain for 6 is 6, 3, 10, 5, 16, 8, 4, 2, 1: nine terms. Among all starting numbers from 1 to limit, find the one with the most terms.

Implement longest_collatz_chain(limit).

Chains share their endings, so remembering the length found for each number saves a lot of work. Terms along the way can pass the limit; use 64-bit integers.

Input

limit: The largest starting number to try.

Output

Return the starting number whose chain has the most terms (counting the start and the final 1). If several tie, return the smallest of them.

制約

1 ≤ limit ≤ 100,000

例

例 1
入力:
limit = 6

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

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

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

解説

The chain lengths for 1 to 6 are 1, 2, 8, 3, 6 and 9 terms, so the answer is 6.

例 2
入力:
limit = 10

期待される出力:
expected = 9
入力:
long long limit = 10;

期待される出力:
long long expected = 9;
入力:
long limit = 10;

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

解説

9 gives 20 terms (9, 28, 14, 7, ...), more than any other start up to 10, so the answer is 9.

解き方のヒント

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

ヒント 1

Count the terms of one chain first, including the start and the 1.

ヒント 2

When a chain reaches a number whose length you already know, add instead of continuing.

ヒント 3

Only replace the best start when a length is strictly greater.

目安の計算量

O(limit × average new steps) time, O(limit) extra space

参考資料

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

ランキング

全体ランキング

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

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

他の人の解答から学ぶ

コミュニティの解答

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