Write a program to check whether the number is a special number or not.
Answers
This program checks whether a number is a Special Number or not.
A number is said to be special number when the sum of factorial of its digits is equal to the number itself.
Example- 145 is a Special Number as 1!+4!+5!=145.
Program-
import java.util.*;
public class SpecialNumberCheck
{
public static void main(String args[])
{
Scanner ob=new Scanner(System.in);
System.out.println("Enter the number to be checked.");
int num=ob.nextInt();
int sum=0;int temp=num;
while(temp!=0)
{
int a=temp%10;int fact=1;
for(int i=1;i<=a;i++)
{
fact=fact*i;
}
sum=sum+fact;
temp=temp/10;
}
if(sum==num)
{
System.out.println(num+" is a Special Number.");
}
else
{
System.out.println(num+" is not a Special Number.");
}
}
}
Description-
The program checks if the number is Special Number.We input the number through Scanner class and sum is variable which stores the sum of factorial of digits.A temp variable is taken.The while loop calculates the sum of factorial of digits.
Inside the loop factorial of last digit is calculated and added to the sum. Every time 'fact' is initialized to 1 as for every digit we have its own factorial.the variable temp is divided by 10 each time so that we can get last digit and then second last digit and so on.
If sum equals number then the resultant statements are printed.
Below are the python program and the output for the above question :
Output :
If the user input as 59, then it will print the special number.
If the user input as 22, then it will print not the special number.
Explanation:
Total=0#variable to calculate the total value.
product=1#variable to calculate the product.
number=input("Enter the number to check for special number: ")#take the number from the user.
for x in number:#for loop to read the number.
Total=Total+int(x)#calculate the total.
product=product*int(x)#clculate the product.
if((product+Total)==int(number)):#check that the number is special or not.
print("The number is a special number")
else:
print("The number is not a special number")
Code Explanation :
- The above code is in python language, in which the first line will takes the input from the user.
- Then the loop will find the product and sum of the digit of the number.
- Then the condition check for the special number by adding the product and the sum.
Learn More :
- Python : https://brainly.in/question/14689905