Tutte le sfide
Facile 0 risolte 0% di accettazione

Factorial Digit Sum

Add up the decimal digits of n factorial.

Cosa imparerai

  • Multiply a digit array by a small number
  • Sum the digits of a large number
  • Remember that 0! = 1

Problema

Mostra traduzione

n! = 1 × 2 × ... × n grows faster than any power: 25! already has 26 digits. Compute n! exactly and add up its digits. Without big integers, store the number as an array of digits and multiply it by 2, 3, ..., n in turn.

Implement factorial_digit_sum(n).

Input

n: The number whose factorial is taken.

Output

Return the sum of the decimal digits of n!. Note that 0! = 1.

Vincoli

0 ≤ n ≤ 1000

Esempi

Esempio 1
Input:
n = 5

Output atteso:
expected = 3
Input:
long long n = 5;

Output atteso:
long long expected = 3;
Input:
long n = 5;

Output atteso:
long expected = 3;

Spiegazione

5! = 120 and 1 + 2 + 0 = 3.

Esempio 2
Input:
n = 0

Output atteso:
expected = 1
Input:
long long n = 0;

Output atteso:
long long expected = 1;
Input:
long n = 0;

Output atteso:
long expected = 1;

Spiegazione

0! is 1 by definition, so the answer is 1.

Come affrontarlo

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

Suggerimento 1

Start from 1 and multiply by 2, 3, ..., n.

Suggerimento 2

Multiply each digit, add the carry, keep the last digit and carry the rest.

Suggerimento 3

When the carry is still left over at the end, it becomes new digits.

Complessità attesa

O(n × D) time where D is the digit count of n!, O(D) 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.