Tutte le sfide
Facile 0 risolte 0% di accettazione

Strong Number

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

Cosa imparerai

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

Problema

Mostra traduzione

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.

Vincoli

0 ≤ n ≤ 10^9

Esempi

Esempio 1
Input:
n = 145

Output atteso:
expected = True
Input:
long long n = 145;

Output atteso:
bool expected = true;
Input:
long n = 145;

Output atteso:
bool expected = true;

Spiegazione

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

Esempio 2
Input:
n = 123

Output atteso:
expected = False
Input:
long long n = 123;

Output atteso:
bool expected = false;
Input:
long n = 123;

Output atteso:
bool expected = false;

Spiegazione

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

Come affrontarlo

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

Suggerimento 1

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

Suggerimento 2

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

Suggerimento 3

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

Complessità attesa

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