Special numbers are those where the sum of the factorial values of each digits of the number is equal to the number itself. Here we will check whether a number is special or not using BlueJ program.
Codes of the program
import java.io.*;
class Word
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n,sum=0;
int i,j;
public void take() throws Exception
{
System.out.println("Enter the number:");
n=Integer.parseInt(br.readLine().trim());
for(i=n;i>0;i=i/10)
{
sum=sum+fact(i%10);
}
if(sum==n)
System.out.println(n+ "is a special number.");
else
System.out.println(n+ "is not a special number.");
}
int fact(int x)
{
int f=1;
for(j=2;j<=x;j++)
f=f*j;
return f;
}
public static void main(String args[]) throws Exception
{
Word ob=new Word();
ob.take();
}
}
Technical analysis of the program
Each digit of the entered number is extracted using a for loop and the digit is passed to a function ‘int fact (int)’ where factorial values of the digit is calculated and returned. The addition value of the factorial values are stored in a variable and at the end the number entered and the sum of factorial values are checked for equality or not.
Similar Programs:
please can you help me?
ReplyDeletewhy isn't this working:
public class Special
{static int fac, sum=0, numCopy, num;
public static void main(String[] args)
{System.out.println("Special numbers between 100 and 150 are:");
for(num=100; num<=150; num++)
{for(numCopy=num; numCopy>0; numCopy/=10)
{sum+=factorial(numCopy%10);}
if(sum==num) System.out.println(numCopy+" is a special number (:");
}
}
public static int factorial(int a)
{fac=1;
for(int x=0; x<=a; x++)
{fac*=x;}
return fac;
}
}
thanks.
Modified codes:
ReplyDeletepublic class Bill
{
static int fac, sum=0, numCopy, num;
public static void main(String[] args)
{
System.out.println("Special numbers between 100 and 150 are:");
for(num=100; num<=150; num++)
{
sum=0;
for(numCopy=num; numCopy>0; numCopy/=10)
{
sum+=factorial(numCopy%10);
}
if(sum==num)
System.out.println(num+" is a special number (:");
}
}
public static int factorial(int a)
{
fac=1;
for(int x=1; x<=a; x++)
{
fac*=x;
}
return fac;
}
}
Can you explain me what do we do to test whether a number is armstrong or not?....with the solution plz explain the program!!
ReplyDeleteProgram on armstrong number is posted in my site. Please search it.
Deleteimport java.util.*;
ReplyDeleteclass Special
{
public static void main()
{
Scanner sc=new Scanner (System.in);
System.out.println("Enter a no. to check if it's a special no or not.");
int s=sc.nextInt();
Special obj=new Special();
if(obj.Test(s)==true)
System.out.println("Special no.");
else
System.out.println("Not a special no.");
}
public boolean Test(int a)
{
int s=0;
int copy=a;
while(a>0)
{
int dg=a%10;
int f=1;
for(int i=1;i<=dg;i++)
f=f*i;
s=s+f;
a=a/10;
}
if(s==copy)
return true;
return false ;
}
}