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
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:
- Accept the number.
- Divide the number by 10 until the quotient is not zero.
- Display the sum.
- Count the number of factors of sum.
- Check if count == 2. If true, sum is a prime number else not.
Variable Description:
Refer to the attachment for output.
•••♪
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.");
}
}