문제
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
예시
입력:
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".
입력:
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에 맞게 수정되었습니다. 위의 설명과 제한 조건을 따르세요.