Computer Science, asked by gitasubashini, 1 month ago

Write a program to accept a number and find the sum of the digits. The program also checks
whether the sum of the digits is a prime number or not and displays an appropriate message.
Sample input: 458
Sample output: The sum of the digits = 17
17 is a prime number

Answers

Answered by anindyaadhikari13
4

Answer:

The given program is written in Java.

import java.util.*;

public class Sum    {

   public static void main(String args[])  {

       Scanner sc=new Scanner(System.in);

       int n,s=0,c=0,i;

       System.out.print("Enter a number: ");

       n=sc.nextInt();

       while(n!=0) {

           s+=n%10;

           n/=10;

       }

       for(i=1;i<=s;i++)   {

           if(s%i==0)

               c++;

       }

       System.out.println("Sum of the digits is: "+s);

       if(c==2)

           System.out.println("Sum of the digits is a prime number.");

       else

           System.out.println("Sum of the digits is not a prime number.");

   }

}

Algorithm:

  1. Accept the number.
  2. Divide the number by 10 until the quotient is not zero.
  3. Display the sum.
  4. Count the number of factors of sum.
  5. Check if count == 2. If true, sum is a prime number else not.

Variable Description:

\dag\ \boxed{\begin{array}{c|c|c}\tt {N}ame:&amp;\tt Type:&amp;\tt Function:\\ \sf n&amp;\sf int&amp;\sf Storing\:\:the\:\:number.\\ \sf s&amp;\sf int&amp;\sf Sum\:\:of\:\:digits\:\:of\:\:n.\\ \sf c&amp;\sf int&amp;\sf Counter.\\ \sf i&amp;\sf int&amp;\sf {L}oop\:\:Variable.\end{array}}

Refer to the attachment for output.

•••♪

Attachments:
Answered by BrainlyProgrammer
2

The following program is done in Java

import java.util.*;

public class Sum{

public static void main(String args[]){

Scanner sc=new Scanner(System.in);

int n,s=0,c=0,i;

System.out.print("Enter a number: ");

for(n=sc.nextInt();n!=0;n/=10){

s+=n%10;

}

for(i=1;i<=s;i++){

c=(s%i==0)?c+1:c+0;

}

System.out.println("Sum of the digits is: "+s);

if(c==2)

System.out.println("Sum of the digits is a prime number.");

else

System.out.println("Sum of the digits is not a prime number.");

}

}

Similar questions