Fácil 0 resolvidos 0% de aceitação

Strong Number

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

O que você vai aprender

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

Problema

Ver tradução

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.

Restrições

0 ≤ n ≤ 10^9

Exemplos

Exemplo 1
Entrada:
n = 145

Saída esperada:
expected = True
Entrada:
long long n = 145;

Saída esperada:
bool expected = true;
Entrada:
long n = 145;

Saída esperada:
bool expected = true;

Explicação

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

Exemplo 2
Entrada:
n = 123

Saída esperada:
expected = False
Entrada:
long long n = 123;

Saída esperada:
bool expected = false;
Entrada:
long n = 123;

Saída esperada:
bool expected = false;

Explicação

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

Como abordar

Tente sozinho primeiro e depois abra uma dica de cada vez.

Dica 1

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

Dica 2

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

Dica 3

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

Complexidade esperada

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

Referências

Este desafio foi adaptado para o CodeUtility. Siga o enunciado e as restrições acima.

A melhor solução aprovada de cada programador. As mais rápidas, leves e mais bem avaliadas ficam no topo.

Ainda não há soluções aprovadas. Resolva e fique com o primeiro lugar.

Aprenda com outros

Soluções da comunidade

Ainda não há soluções publicadas. Resolva este desafio para compartilhar a primeira.