Question
Program to print Smith number in a given range.
(A Smith Number is a composite number whose sum of digits is equal to the sum of digits in its prime factorization)
Enter a lower Range:
1
Enter Upper Range:50
Smith Numbers:
4 22 27
Enter a lower Range:1
Enter Upper Range:500
Smith Numbers:
4 22 27 58 85 94 121 166 202 265 274 319 346 355 378 382 391 438 454 483
Share code with your friends
Share on whatsapp
Share on facebook
Share on twitter
Share on telegram
Code
import java.util.Scanner;
public class SmithNumberInGivenRange
{
public static boolean isPrime(int number)
{
int k=0;
for(k=2;k<=(number/2);k++)
{
if(number%k==0)
{
return false;
}
}
return true;
}
public static void main()
{
int sumd=0,sump=0,i=0,temp=0,temp1=0,lowerRange=0,upperRange=0,j=0;
Scanner sc=new Scanner(System.in);
System.out.print("Enter a lower Range:");
lowerRange=sc.nextInt();
System.out.print("Enter Upper Range:");
upperRange=sc.nextInt();
System.out.println("Smith Numbers:");
for(i=lowerRange;i<=upperRange;i++)
{
temp=i;
sumd=0;
sump=0;
while(temp>0)
{
sumd=sumd+(temp%10);
temp=temp/10;
}
temp=i;
for(j=2;j<=i/2;j++)
{
while(temp%j==0)
{
if(j<4)
{
sump=sump+j;
temp=temp/j;
}
else
{
if(isPrime(j)==true)
{
temp1=j;
while(temp1>0)
{
sump=sump+(temp1%10);
temp1=temp1/10;
}
temp=temp/j;
}
}
}
}
if(sumd==sump)
{
System.out.print(i+" ");
}
}
}
}