Write a program to input a number and print whether the number is a special number or not. (A number is said to be a special number if the sum of the factorial of the digits of the number is the same as the original number).
Example: 145 is a special number because 1! + 4! + 5! = 1 + 24 + 120 = 145 (where ! denotes factorial of the number, and the factorial value of a number is the product of all integers from 1 to that number, e.g., 5! = 1 × 2 × 3 × 4 × 5 = 120).
import java.io.*;
class Special {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n, r, f, i;
int sum = 0;
int originalNumber;
System.out.println("Enter a number:");
n = Integer.parseInt(br.readLine());
originalNumber = n;
while (n > 0) {
r = n % 10; // Extract the last digit
f = 1; // Initialize factorial
for (i = 1; i <= r; i++) {
f *= i; // Calculate factorial
}
sum += f; // Add factorial to the sum
n /= 10; // Remove the last digit
}
if (sum == originalNumber) {
System.out.println("Special number.");
} else {
System.out.println("Not a Special number.");
}
}
}
| Variable | Type | Description |
|---|---|---|
n |
int |
The number input by the user. |
originalNumber |
int |
Stores the original number for comparison. |
r |
int |
Stores the current digit extracted from the number. |
f |
int |
Stores the factorial of the current digit. |
i |
int |
Loop variable for calculating factorial. |
sum |
int |
Sum of the factorials of the digits. |
This table summarizes the variables used in the program and their purposes.
Input Reading:
BufferedReader to read the input number from the user.Initialize Variables:
n is the number entered by the user.originalNumber stores the original number for comparison later.sum is used to accumulate the sum of the factorials of the digits.Calculate Factorials:
n using n % 10.sum.Check Special Number:
sum of the factorials to the originalNumber.Make sure you compile and run this program in a Java environment. This program will correctly identify whether a number is a special number based on the criteria provided.
First read the algorithm, then study the program code line by line. After that, compare the code with the output and finally go through the explanation. This approach helps learners understand both the logic and the implementation properly.
After understanding this example, try to rewrite the same program without looking at the code. Then change some values or logic and run it again. This helps improve confidence and keeps learners engaged on the page for longer.