Fácil 0 resueltos 0% de aceptación

Strong Number

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

Lo que aprenderás

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

Problema

Ver traducción

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.

Restricciones

0 ≤ n ≤ 10^9

Ejemplos

Ejemplo 1
Entrada:
n = 145

Salida esperada:
expected = True
Entrada:
long long n = 145;

Salida esperada:
bool expected = true;
Entrada:
long n = 145;

Salida esperada:
bool expected = true;

Explicación

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

Ejemplo 2
Entrada:
n = 123

Salida esperada:
expected = False
Entrada:
long long n = 123;

Salida esperada:
bool expected = false;
Entrada:
long n = 123;

Salida esperada:
bool expected = false;

Explicación

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

Cómo abordarlo

Inténtalo primero por tu cuenta y luego abre las pistas una a una.

Pista 1

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

Pista 2

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

Pista 3

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

Complejidad esperada

O(d) time for d digits, O(1) extra space

Referencias

Este reto está adaptado para CodeUtility. Sigue el enunciado y las restricciones indicadas arriba.

Clasificación

Clasificación completa

La mejor solución aprobada de cada programador. Las más rápidas, ligeras y mejor valoradas van primero.

Aún no hay soluciones aprobadas. Resuélvelo y quédate el primer puesto.

Aprende de otros

Soluciones de la comunidad

Aún no hay soluciones publicadas. Resuelve este reto para compartir la primera.