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).
Java Programming Language (Article) (Program)
34
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).
Program:
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."); } } }
Output:
Explanation:
Table of Variables
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:
- Uses
BufferedReader
to read the input number from the user.
- Uses
-
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:
- Extracts each digit from
n
usingn % 10
. - Calculates the factorial of each digit.
- Adds the factorial value to
sum
.
- Extracts each digit from
-
Check Special Number:
- Compares the
sum
of the factorials to theoriginalNumber
. - Prints whether the number is a special number or not.
- Compares the
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.
This Particular section is dedicated to Programs only. If you want learn more about Java Programming Language. Then you can visit below links to get more depth on this subject.