Tous les défis
Facile 0 résolus 0 % de réussite

Self Powers Tail

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

Ce que vous allez apprendre

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

Problème

Afficher la traduction

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.

Contraintes

1 ≤ n ≤ 5000; 1 ≤ k ≤ 9

Exemples

Exemple 1
Entrée :
n = 4
k = 3

Sortie attendue :
expected = "288"
Entrée :
long long n = 4;
long long k = 3;

Sortie attendue :
std::string expected = "288";
Entrée :
long n = 4;
long k = 3;

Sortie attendue :
string expected = "288";

Explication

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

Exemple 2
Entrée :
n = 3
k = 4

Sortie attendue :
expected = "0032"
Entrée :
long long n = 3;
long long k = 4;

Sortie attendue :
std::string expected = "0032";
Entrée :
long n = 3;
long k = 4;

Sortie attendue :
string expected = "0032";

Explication

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

Comment l'aborder

Essayez d'abord seul, puis ouvrez les indices un par un.

Indice 1

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

Indice 2

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

Indice 3

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

Complexité attendue

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

Références

Ce défi a été adapté pour CodeUtility. Suivez l'énoncé et les contraintes ci-dessus.

La meilleure solution validée de chaque codeur. Les plus rapides, les plus légères et les mieux notées passent devant.

Aucune solution validée pour l'instant. Résolvez-le et prenez la première place.

Apprenez des autres

Solutions de la communauté

Aucune solution publiée pour l'instant. Résolvez ce défi pour partager la première.