ง่าย 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

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 กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน

คำตอบที่ผ่านดีที่สุดของแต่ละคน คำตอบที่เร็วกว่า ใช้หน่วยความจำน้อยกว่า และได้คะแนนดีกว่าจะอยู่ด้านบน

ยังไม่มีคำตอบที่ผ่าน แก้โจทย์นี้แล้วคว้าอันดับหนึ่งไปเลย

เรียนรู้จากคนอื่น

แนวทางจากชุมชน

ยังไม่มีวิธีทำที่เผยแพร่ ลองแก้โจทย์นี้เพื่อแชร์วิธีแรก