Facile 0 résolus 0 % de réussite

Strong Number

Check whether a number equals the sum of the factorials of its digits.

Ce que vous allez apprendre

  • Split a number into its digits with % and /
  • Precompute small factorials once
  • Compare a computed total with the original number

Problème

Afficher la traduction

A strong number is a number that equals the sum of the factorials of its digits. For example, 145 is strong because 1! + 4! + 5! = 1 + 24 + 120 = 145. Mathematicians call these numbers *factorions*; in base 10 there are only four of them, but your program should test the definition rather than a list.

Implement strong_number(n).

Use this definition: take each decimal digit d of n, add up d! for all of them (with 0! = 1), and compare the total with n. So 0 is not strong, because 0! = 1.

Input

n: The number to test.

Output

Return true if the sum of the factorials of the digits of n equals n, otherwise false.

Contraintes

0 ≤ n ≤ 10^9

Exemples

Exemple 1
Entrée :
n = 145

Sortie attendue :
expected = True
Entrée :
long long n = 145;

Sortie attendue :
bool expected = true;
Entrée :
long n = 145;

Sortie attendue :
bool expected = true;

Explication

1! + 4! + 5! = 1 + 24 + 120 = 145, which is the number itself, so the answer is true.

Exemple 2
Entrée :
n = 123

Sortie attendue :
expected = False
Entrée :
long long n = 123;

Sortie attendue :
bool expected = false;
Entrée :
long n = 123;

Sortie attendue :
bool expected = false;

Explication

1! + 2! + 3! = 1 + 2 + 6 = 9, and 9 ≠ 123, so the answer is false.

Comment l'aborder

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

Indice 1

Keep a copy of n, because you will change the working value while taking digits off.

Indice 2

Only the factorials of 0 to 9 are ever needed, so build them once.

Indice 3

Check what your loop does when n is 0: it has one digit.

Complexité attendue

O(d) time for d digits, 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.