Array-promo

Question

Program to Check whether a given number is a Smith number only using main method.
(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 void main()
    {
        int sumd=0,sump=0,n=0,i=0,j=0,temp=0,temp1=0,flag=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)
            {

                flag=0;
                //checking whether number is prime number or not
                for(j=2;j< i;j++)
                {

                    if(i%j==0)
                    {
                        flag=1;
                        break;
                    }
                } 
                //if number is prime then only it is added to sump
                if(flag==0)
                {
                    temp1=i;
                    //Extracting digits if i >9 and then adding extracted digits to sump
                    while(temp1>0)
                    {
                        sump=sump+(temp1%10);   
                        temp1=temp1/10;   
                    }
                    temp=temp/i;

                }

            }
        }

        if(sumd==sump && n>0)
        {
            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 *