This program checks whether a number is a Special Number or not.
A number is said to be a special number when the sum of the 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 a=ob.nextInt();
int sum=0,b=a;
while(a!=0)//or a>0
{
int rem=a%10;
int fact=1;
for(int i=1;i<=rem;i++)
{
fact=fact*i;
}
sum=sum+fact;
a=a/10;
}
if(b==sum)
{
System.out.println(a+" is a Special Number.");
}
else
{
System.out.println(a+" is not a Special Number.");
}
}
}*/
//____________________________
Description-
The program checks if the number is a Special Number. We input the number through the Scanner class and
the sum is a variable that stores the sum of the factorial of digits. A temp variable is taken. The while loop
calculates the sum of the factorial digits.
Inside the loop factorial of the 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 the last digit and then the second last digit and so on.
If the sum equals a number then the resultant statements are printed.
import java.util.*;
public class SpecialNumberCheck
{
public static void main(String args[])
{
int sum=0,a,i,b;
Scanner ob=new Scanner(System.in);
System.out.println("Enter the number to be checked.");
a=ob.nextInt();
b=a;//initialize a variable equal to the number as we can not
// modify original number since we will require it later
while(b>0)//or a>0
{
int rem=a%10;
sum=sum+rem;
b=b/10;
}
if (a % sum == 0) {
System.out.println(a+" is a Niven Number.");
}
else
{
System.out.println(a+" is not a Niven Number.");
}
}
}
Comments
Post a Comment
Please, do not enter any spam link in the comment box.