簡単 0件解決済み 正答率0%

Self Powers Tail

Find the last k digits of 1^1 + 2^2 + ... + n^n.

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

  • Reduce sums and products modulo 10^k
  • Compute powers with repeated squaring
  • Format a number with leading zeros

問題

翻訳を表示

The sum 1^1 + 2^2 + 3^3 + ... + n^n has thousands of digits even for modest n, but only its tail is needed. Find its last k digits. Work modulo 10^k from the start: reduce after every multiplication and every addition, and the numbers stay small.

Implement self_powers_tail(n, k).

Input

n: The last term of the sum.

k: How many trailing digits to return.

Output

Return the last k digits as a string of exactly k characters, padded with leading zeros if needed.

制約

1 ≤ n ≤ 5000; 1 ≤ k ≤ 9

例

例 1
入力:
n = 4
k = 3

期待される出力:
expected = "288"
入力:
long long n = 4;
long long k = 3;

期待される出力:
std::string expected = "288";
入力:
long n = 4;
long k = 3;

期待される出力:
string expected = "288";

解説

1 + 4 + 27 + 256 = 288, so the last three digits are "288".

例 2
入力:
n = 3
k = 4

期待される出力:
expected = "0032"
入力:
long long n = 3;
long long k = 4;

期待される出力:
std::string expected = "0032";
入力:
long n = 3;
long k = 4;

期待される出力:
string expected = "0032";

解説

1 + 4 + 27 = 32, padded to four digits: "0032".

解き方のヒント

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

ヒント 1

Only the last k digits matter, so reduce modulo 10^k after every step.

ヒント 2

i^i can be found by repeated squaring, or by multiplying i times with reduction.

ヒント 3

Pad the final value on the left with zeros to get exactly k characters.

目安の計算量

O(n log n) time, O(1) extra space

参考資料

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

ランキング

全体ランキング

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

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

他の人の解答から学ぶ

コミュニティの解答

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