Dễ 0 đã giải Tỷ lệ chấp nhận 0%

Self Powers Tail

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

Bạn sẽ học được gì

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

Đề bài

Xem bản dịch

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.

Ràng buộc

1 ≤ n ≤ 5000; 1 ≤ k ≤ 9

Ví dụ

Ví dụ 1
Đầu vào:
n = 4
k = 3

Kết quả mong đợi:
expected = "288"
Đầu vào:
long long n = 4;
long long k = 3;

Kết quả mong đợi:
std::string expected = "288";
Đầu vào:
long n = 4;
long k = 3;

Kết quả mong đợi:
string expected = "288";

Giải thích

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

Ví dụ 2
Đầu vào:
n = 3
k = 4

Kết quả mong đợi:
expected = "0032"
Đầu vào:
long long n = 3;
long long k = 4;

Kết quả mong đợi:
std::string expected = "0032";
Đầu vào:
long n = 3;
long k = 4;

Kết quả mong đợi:
string expected = "0032";

Giải thích

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

Hướng tiếp cận

Hãy tự thử trước, sau đó mở từng gợi ý một.

Gợi ý 1

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

Gợi ý 2

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

Gợi ý 3

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

Độ phức tạp mong đợi

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

Tham khảo

Thử thách này đã được điều chỉnh cho CodeUtility. Hãy làm theo đề bài và các ràng buộc ở trên.

Lời giải đạt tốt nhất của mỗi người. Lời giải nhanh hơn, tốn ít bộ nhớ hơn và được đánh giá cao hơn sẽ đứng trên.

Chưa có lời giải nào đạt. Giải bài này để giành hạng nhất.

Học hỏi từ người khác

Giải pháp cộng đồng

Chưa có giải pháp nào được chia sẻ. Hãy giải thử thách này để đăng giải pháp đầu tiên.