Strong Number — Solution in Python, Java & C++
Strong Number solution explained: step-by-step approach, complexity and code in Python, Java, C++ and JavaScript. An easy problem, asked at TCS and Infosys.
Strong Number is an easy coding problem on math, asked in TCS, Infosys, Wipro and Tech Mahindra interviews.
- Difficulty: Easy
- Topics: Math
- Asked at: TCS, Infosys, Wipro, Tech Mahindra
- Time limit: 2 s
- Memory limit: 256 MB
- Languages: JavaScript, TypeScript, Python, Java, C++, C, C#, Go, Kotlin, Swift, Rust, PHP and Ruby
Problem statement
A strong number (sometimes called a Krishnamurthy number) is a number equal to the sum of the factorials of its digits.
Given a positive integer n, return true if n is a strong number.
Example 1
Input: n = 145
Output: true
Explanation: 1! + 4! + 5! = 1 + 24 + 120 = 145.
Example 2
Input: n = 132
Output: false
Explanation: 1! + 3! + 2! = 1 + 6 + 2 = 9, not 132.
Example 3
Input: n = 40585
Output: true
Explanation: 4! + 0! + 5! + 8! + 5! = 40585.
Constraints
1 <= n <= 1000000! = 1.
Hints for Strong Number
Hint 1
There are only ten possible digits, so precompute 0! … 9! once instead of recomputing per digit.
Hint 2
Remember that 0! = 1, not 0 — this is the case most solutions get wrong.
Hint 3
Peel digits with
% 10and/ 10and accumulate.
How to solve Strong Number
Precompute 0!…9! once, then sum the factorial of each digit and compare with the original number.
Approach
- Table
fact = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]. - Peel digits with
% 10and// 10, addingfact[digit]to a total. - Return
total == n.
Why it works
The definition is a direct sum over digits; a ten-entry table removes any repeated factorial computation and keeps the loop a single lookup per digit.
Complexity
- Time —
O(digits) - Space —
O(1)
Pitfalls
0! = 1, not0— a computed table that starts at zero breaks numbers containing a zero digit.- There are only four strong numbers (1, 2, 145, 40585), so the answer is usually
false.
Reference solution
Python
def isStrongNumber(n: int) -> bool:
fact = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880]
total, x = 0, n
while x > 0:
total += fact[x % 10]
x //= 10
return total == nJava
public static boolean isStrongNumber(int n) {
int[] fact = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};
long total = 0;
int x = n;
while (x > 0) {
total += fact[x % 10];
x /= 10;
}
return total == n;
}C++
bool isStrongNumber(int n) {
int fact[10] = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};
long long total = 0;
int x = n;
while (x > 0) {
total += fact[x % 10];
x /= 10;
}
return total == (long long) n;
}JavaScript
var isStrongNumber = function(n) {
const fact = [1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880];
let total = 0, x = n;
while (x > 0) {
total += fact[x % 10];
x = Math.floor(x / 10);
}
return total === n;
};Also on the editorial tab: C, C#, Go, Kotlin, PHP, Ruby, Rust, Swift, TypeScript.