Getting everything ready for you…

Loading courses, problems and your progress. This takes just a moment.

0s

Practice › Basics

Strong Number

Easy · Basics · Asked at TCS, Infosys, Wipro, Accenture, Cognizant

A number is strong if the sum of the factorials of its digits equals the number itself — for example 145 = 1! + 4! + 5! = 1 + 24 + 120.

Print YES if n is a strong number, otherwise NO.

Input

A single integer n.

Output

YES or NO.

Constraints

Pre-compute 0! … 9! once, then add the factorial of each digit.

Example 1

Input

145

Output

YES

Example 2

Input

123

Output

NO

Hints

  1. Only ten factorials are ever needed: 0! to 9!.
  2. Take the digits one by one (n % 10, then n / 10) and add their factorials.

Approach

Store 0! … 9! in an array. Walk over the digits of n, add the factorial of each digit, and compare the total with n. Only four strong numbers exist at all (1, 2, 145, 40585), but the direct check is what interviewers want to see.

Complexity: O(number of digits) time · O(1) space

Solution

C++ solution

#include <bits/stdc++.h>
using namespace std;

int main() {
    long long n;
    cin >> n;
    int fact[10] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};
    long long sum = 0;
    for (long long t = n; t > 0; t /= 10) sum += fact[t % 10];
    cout << (sum == n ? "YES" : "NO") << "\n";
    return 0;
}

Python solution

n = int(input())
fact = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
total = sum(fact[int(d)] for d in str(n))
print("YES" if total == n else "NO")

Java solution

import java.util.*;

public class Main {
    public static void main(String[] args) {
        long n = new Scanner(System.in).nextLong();
        int[] fact = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};
        long sum = 0;
        for (long t = n; t > 0; t /= 10) sum += fact[(int) (t % 10)];
        System.out.println(sum == n ? "YES" : "NO");
    }
}

Solve Strong Number online · All practice problems