簡単 0件解決済み 正答率0%

Strong Number

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

このチャレンジで学べること

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

問題

翻訳を表示

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.

制約

0 ≤ n ≤ 10^9

例

例 1
入力:
n = 145

期待される出力:
expected = True
入力:
long long n = 145;

期待される出力:
bool expected = true;
入力:
long n = 145;

期待される出力:
bool expected = true;

解説

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

例 2
入力:
n = 123

期待される出力:
expected = False
入力:
long long n = 123;

期待される出力:
bool expected = false;
入力:
long n = 123;

期待される出力:
bool expected = false;

解説

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

解き方のヒント

まずは自分で考えてから、ヒントを 1 つずつ開いてみましょう。

ヒント 1

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

ヒント 2

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

ヒント 3

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

目安の計算量

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

参考資料

この課題はCodeUtility用に調整されています。上記の説明と制約に従ってください。

ランキング

全体ランキング

コーダーごとのいちばん良い合格解答です。速く、メモリが少なく、評価が高い解答ほど上位になります。

まだ合格した解答はありません。解いて 1 位になりましょう。

他の人の解答から学ぶ

コミュニティの解答

まだ公開された解答がありません。この課題を解いて最初の解答を共有しましょう。