Check Strong Number in Java
Problem
A strong number is a number equal to the sum of the factorials of its own digits.
Given a number, determine whether it is a strong number.
Java Program
public class StrongCheck {
static int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; i++) {
result *= i; // multiply every integer from 2 up to n
}
return result;
}
public static void main(String[] args) {
int num = 145;
int original = num;
int sum = 0;
while (num > 0) {
int digit = num % 10; // peel off the last digit
sum += factorial(digit);
num /= 10;
}
System.out.println(original + " is a strong number: " + (sum == original));
}
}Output
Core Logic
Extracting each digit, computing its factorial, and summing the results checks the definition directly.
- 1
factorial(n)is a small helper that multiplies every integer from2up tontogether. - 2The main loop peels off one digit at a time with
num % 10, then removes it fromnumwithnum /= 10. - 3Each digit's factorial is computed with the helper and added into
sum. - 4Once every digit has been processed,
sumis compared against the original number.
145, the digits 1, 4, 5 have factorials 1, 24, and 120 — summing to 145, which matches the original number.Key Point: Unlike Armstrong numbers, which raise digits to a power that depends on the digit count, strong numbers always use the digit's own factorial — the definition never changes based on how many digits the number has.
Why: The loop runs once per digit, and each digit's factorial only ever multiplies up to 9 numbers together, since digits never exceed 9.
Key Concepts
Approach 2: Java 8
public class StrongCheckStream {
public static void main(String[] args) {
int num = 145;
int[] factorials = new int[10];
factorials[0] = 1;
for (int i = 1; i <= 9; i++) {
factorials[i] = factorials[i - 1] * i; // each factorial builds on the one before it
}
// Looks up each digit's precomputed factorial and sums them
int sum = String.valueOf(num).chars()
.map(c -> factorials[c - '0'])
.sum();
System.out.println(num + " is a strong number: " + (sum == num));
}
}
Output
Core Logic
Since digits only ever range from 0 to 9, their factorials can be precomputed once into a small lookup array, then summed with a stream.
- 1
factorialsis a fixedint[10]array holding0!through9!, built once with a loop. - 2
String.valueOf(num).chars()returns anIntStreamof the number's digit characters. - 3
.map(c -> factorials[c - '0'])looks up each digit's precomputed factorial directly, instead of recomputing it. - 4
.sum()reduces the stream of factorials down to a single total.
145, the stream looks up factorials[1], factorials[4], and factorials[5] — 1, 24, and 120 — summing to 145.Key Point: Precomputing the factorials once, outside the stream, avoids recalculating the same small set of factorials from scratch for every digit.
Why: The lookup table has a fixed size of 10 regardless of the number's magnitude, and the stream still visits each digit once.