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

Digit Factorial Chains

Count starting numbers whose digit factorial chain has exactly a given number of distinct terms.

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

  • Follow a chain until a value repeats
  • Find chain lengths inside and before a loop
  • Reuse stored lengths

問題

翻訳を表示

Replace a number by the sum of the factorials of its digits: 145 gives 1! + 4! + 5! = 145 again, and 69 gives 6! + 9! = 363600. Repeating this always falls into a loop. The chain of a start is its terms until the first repeat: 69, 363600, 1454, 169, 363601 and then 1454 again, so 69 has 5 distinct terms. Count the starting numbers from 1 to limit whose chain has exactly length distinct terms.

Implement digit_factorial_chains(limit, length).

Many chains run into the same numbers. Store each number's chain length once it is known and reuse it.

Input

limit: The largest starting number.

length: The number of distinct terms wanted, the start included.

Output

Return how many starting numbers n with 1 ≤ n ≤ limit have exactly length distinct terms in their chain.

制約

1 ≤ limit ≤ 100,000; 1 ≤ length ≤ 70

例

例 1
入力:
limit = 2
length = 1

期待される出力:
expected = 2
入力:
long long limit = 2;
long long length = 1;

期待される出力:
long long expected = 2;
入力:
long limit = 2;
long length = 1;

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

解説

1! = 1 and 2! = 2, so 1 and 2 each map to themselves and have a chain of 1 term. The answer is 2.

例 2
入力:
limit = 10
length = 2

期待される出力:
expected = 1
入力:
long long limit = 10;
long long length = 2;

期待される出力:
long long expected = 1;
入力:
long limit = 10;
long length = 2;

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

解説

3 gives 6, then 720, 5043, ... so it is long. 10 gives 1! + 0! = 2 and then 2 again: two terms. Only 10 has exactly 2, so the answer is 1.

解き方のヒント

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

ヒント 1

Precompute 0! to 9! once.

ヒント 2

Record each value's step number in the current chain; a repeat tells you where the loop starts.

ヒント 3

Values in the loop all have the loop's length, and each value before it has one more than the next.

目安の計算量

O(limit × log limit) time with memoization, O(limit) extra space

参考資料

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

ランキング

全体ランキング

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

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

他の人の解答から学ぶ

コミュニティの解答

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