Check Strong Number in Java

Check whether a number is a strong number (sum of factorials of digits equals the number).

IntermediateModule 2: Conditional ProgramsExample 7 of 20
check-strong-number.java
1import java.util.Scanner;
2
3public class Main {
4 private static int factorial(int n) {
5 int fact = 1;
6 for (int i = 2; i <= n; i++) {
7 fact *= i;
8 }
9 return fact;
10 }
11
12 public static void main(String[] args) {
13 Scanner sc = new Scanner(System.in);
14
15 System.out.print("Enter a number: ");
16 int n = sc.nextInt();
17
18 int temp = n;
19 int sum = 0;
20 while (temp != 0) {
21 int d = temp % 10;
22 sum += factorial(d);
23 temp /= 10;
24 }
25
26 if (sum == n) {
27 System.out.println(n + " is a Strong Number");
28 } else {
29 System.out.println(n + " is not a Strong Number");
30 }
31
32 sc.close();
33 }
34}

Output

Enter a number: 145
145 is a Strong Number

What's going on

We compute factorial of each digit and add them; if the sum equals the original number, it is strong.