Easy 0 solved 0% acceptance

Strong Number

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

What you'll learn

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

Problem

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.

Constraints

0 ≤ n ≤ 10^9

Examples

Example 1
Input:
n = 145

Expected output:
expected = True
Input:
long long n = 145;

Expected output:
bool expected = true;
Input:
long n = 145;

Expected output:
bool expected = true;

Explanation

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

Example 2
Input:
n = 123

Expected output:
expected = False
Input:
long long n = 123;

Expected output:
bool expected = false;
Input:
long n = 123;

Expected output:
bool expected = false;

Explanation

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

How to approach it

Try on your own first, then open one hint at a time.

Hint 1

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

Hint 2

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

Hint 3

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

Expected complexity

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

References

This challenge is adapted for CodeUtility. Follow the statement and constraints above.

The best passing solution of each coder. Faster, smaller and better-reviewed solutions rank higher.

No passing solutions yet. Solve it to take first place.

Learn from others

Community solutions

No published solutions yet. Solve this challenge to share the first one.