1. Introduction
A Strong Number (or Digital Number) is a number that is equal to the sum of the factorial of its digits. For example, 145 is a strong number, as 1! + 4! + 5! = 1 + 24 + 120 = 145. In this blog post, we will create a Java program to check whether a given number is a strong number or not.
2. Program Steps
1. Define a class named StrongNumber.
2. Inside this class, define the main method.
3. Inside the main method, create a Scanner object to take user input.
4. Prompt the user to enter a number.
5. Declare and initialize variables to store the original number, the sum of factorials of the digits, and the remainder.
6. Create a loop to calculate the sum of the factorial of each digit.
7. Compare the calculated sum with the original number.
8. Print whether the number is a strong number or not.
3. Code Program
import java.util.Scanner; // Import Scanner class
public class StrongNumber { // Step 1: Define a class named StrongNumber
public static void main(String[] args) { // Step 2: Define the main method
Scanner sc = new Scanner(System.in); // Step 3: Create Scanner object to read input
System.out.println("Enter a number: "); // Step 4: Prompt the user to enter a number
int num = sc.nextInt(); // Read the user input
int originalNum = num; // Step 5: Store the original number
int sum = 0; // Initialize sum to 0
// Step 6: Create a loop to calculate the sum of the factorial of each digit
while (num > 0) {
int digit = num % 10; // Get the last digit
int factorial = 1; // Initialize factorial to 1
for (int i = 1; i <= digit; i++) {
factorial *= i; // Calculate factorial of the digit
}
sum += factorial; // Add the factorial to the sum
num /= 10; // Remove the last digit
}
// Step 7: Compare the calculated sum with the original number
if (originalNum == sum) {
System.out.println(originalNum + " is a Strong Number."); // Step 8: Print the result
} else {
System.out.println(originalNum + " is not a Strong Number."); // Step 8: Print the result
}
}
}
Output:
Enter a number: 145 145 is a Strong Number.
4. Step By Step Explanation
– Step 1: A class named StrongNumber is defined.
– Step 2: The main method is defined inside the StrongNumber class.
– Step 3: A Scanner object is created to read the user input.
– Step 4: The user is prompted to enter a number.
– Step 5: The original number is stored and variables for sum and factorial are initialized.
– Step 6: A while loop is used to calculate the sum of the factorial of each digit of the number.
– Step 7: The calculated sum is compared with the original number.
– Step 8: The program prints whether the original number is a Strong Number or not.