Легко Решено: 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

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. Следуйте условию и ограничениям выше.

Лучшее принятое решение каждого участника. Более быстрые, экономные и высоко оценённые решения стоят выше.

Принятых решений пока нет. Решите задачу и займите первое место.

Учитесь у других

Решения сообщества

Пока нет опубликованных решений. Решите задание, чтобы поделиться первым.