Tutte le sfide
Facile 0 risolte 0% di accettazione

Self Powers Tail

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

Cosa imparerai

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

Problema

Mostra traduzione

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.

Vincoli

1 ≤ n ≤ 5000; 1 ≤ k ≤ 9

Esempi

Esempio 1
Input:
n = 4
k = 3

Output atteso:
expected = "288"
Input:
long long n = 4;
long long k = 3;

Output atteso:
std::string expected = "288";
Input:
long n = 4;
long k = 3;

Output atteso:
string expected = "288";

Spiegazione

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

Esempio 2
Input:
n = 3
k = 4

Output atteso:
expected = "0032"
Input:
long long n = 3;
long long k = 4;

Output atteso:
std::string expected = "0032";
Input:
long n = 3;
long k = 4;

Output atteso:
string expected = "0032";

Spiegazione

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

Come affrontarlo

Prova prima da solo, poi apri un suggerimento alla volta.

Suggerimento 1

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

Suggerimento 2

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

Suggerimento 3

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

Complessità attesa

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

Riferimenti

Questa sfida è adattata per CodeUtility. Segui la traccia e i vincoli sopra.

La migliore soluzione superata di ogni programmatore. Le più veloci, leggere e meglio valutate stanno in alto.

Ancora nessuna soluzione superata. Risolvila e prendi il primo posto.

Impara dagli altri

Soluzioni della community

Nessuna soluzione pubblicata. Risolvi questa sfida per condividere la prima.