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

Factorial Digit Sum

Add up the decimal digits of n factorial.

Ce que vous allez apprendre

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

Problème

Afficher la traduction

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.

Contraintes

0 ≤ n ≤ 1000

Exemples

Exemple 1
Entrée :
n = 5

Sortie attendue :
expected = 3
Entrée :
long long n = 5;

Sortie attendue :
long long expected = 3;
Entrée :
long n = 5;

Sortie attendue :
long expected = 3;

Explication

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

Exemple 2
Entrée :
n = 0

Sortie attendue :
expected = 1
Entrée :
long long n = 0;

Sortie attendue :
long long expected = 1;
Entrée :
long n = 0;

Sortie attendue :
long expected = 1;

Explication

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

Comment l'aborder

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

Indice 1

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

Indice 2

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

Indice 3

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

Complexité attendue

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