Java program to check whether the number is special number or not.
Answers
Answer:
This programbchecks 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.");
}
}
}
import java.util.*;
public class JavaHungry {
public static void main(String args[]) {
System.out.println("Enter any number : ");
Scanner scan = new Scanner(System.in);
int inputNumber = scan.nextInt();
boolean result = specialnumber(inputNumber);
if (result == true)
System.out.println(inputNumber + " is a Special number");
if (result == false)
System.out.println(inputNumber + " is NOT a Special number");
}
public static boolean specialnumber(int inputNumber) {
// Create a copy of the inputNumber
int temp = inputNumber;
// Initialize sumOfDigits of inputNumber
int sumOfDigits = 0;
/* Calculate the sum of factorial of
digits */
while (temp != 0) {
// Get the rightmost digit
int currentDigit = temp % 10;
sumOfDigits = sumOfDigits + factorial(currentDigit);
temp = temp/10;
}
/* If sumOfDigits is equal to inputNumber then
the number is Special, otherwise not */
return (sumOfDigits == inputNumber);
}
public static int factorial(int number) {
if (number == 1 || number == 0)
return 1;
else
return (number * factorial(number -1));
}
}