Array-promo

Question

Program to Check whether a given number is a Smith number.
(A Smith Number is a composite number whose sum of digits is equal to the sum of digits in its prime factorization)

				
					Enter a number:4
4 IS A SMITH NUMBER
Prime factorization = 2, 2  and 2 + 2 = 4
Therefore, 4 is a smith number

Enter a number:666
666 IS A SMITH NUMBER
Prime factorization = 2, 3, 3, 37 and
2 + 3 + 3 + (3 + 7) = 6 + 6 + 6 = 18
Therefore, 666 is a smith number
				
			

Share code with your friends

Share on whatsapp
Share on facebook
Share on twitter
Share on telegram

Code

				
					import java.util.Scanner;
public class SmithNumber
{
    public static boolean isPrime(int number)
    {
        int j=0;
        for(j=2;j<=(number/2);j++)
        {

            if(number%j==0)
            {
                return false; 
            }
        }  
        return true;

    }

    public static void main()
    {
        int sumd=0,sump=0,n=0,i=0,temp=0,temp1=0;
        Scanner sc=new Scanner(System.in);
        System.out.print("Enter a number");
        n=sc.nextInt();
        temp=n;
        while(temp>0)
        {
            sumd=sumd+(temp%10);
            temp=temp/10;
        }
        temp=n;
        for(i=2;i<=n/2;i++)
        {
            while(temp%i==0)
            {
                if(i<4)
                {
                    sump=sump+i;
                    temp=temp/i;

                }
                else
                {
                    if(isPrime(i)==true)
                    {
                        temp1=i;
                        while(temp1>0)
                        {
                            sump=sump+(temp1%10);   
                            temp1=temp1/10;   
                        }
                        temp=temp/i;

                    }

                }
            }
        }
        if(sumd==sump)
        {
            System.out.println(n+" IS A SMITH NUMBER");  
        }
        else
        {
            System.out.println(n+" IS NOT A SMITH NUMBER");
        }
    }
}


				
			

Coding Store

Leave a Reply

Your email address will not be published. Required fields are marked *