A prime number is called an Additive prime if the sum of its digits is also a prime
number. Write a program that will display the N (user input) number of additive prime numbers
and displays the output in the following format:
Prime number
Sum of its digits
2
2
3
3
...
11
2
using user-defined functions
Sample output:
Enter an integer: 10
Prime number Sum of Digits
2 2
3 3
5 5
7 7
11 2
23 5
29 11
41 5
43 7
47 11
#include <iostream>
#include <iomanip>
#include <math.h>
using namespace std;
bool isPrime(int num) {
if (num < 2){
return false;
}
if (num == 2 || num == 3){
return true;
}
for (int i = 2; i <= sqrt(num*1.0); i++){
if (num % i == 0){
return false;
}
}
return true;
}
int sumDigits(int number){
int sum = 0;
while (number != 0) {
sum = sum + number % 10;
number = number / 10;
}
return sum;
}
int main(){
int number;
int counter=0;
int i=0;
cout<<"Enter an integer: ";
cin>>number;
cout<<"Prime number\tSum of Digits\n";
while(counter<number){
int sumD=sumDigits(i);
if(isPrime(i) && isPrime(sumD)){
cout<<i<<"\t\t"<<sumD<<"\n";
counter++;
}
i++;
}
cin>>number;
return 0;
}
Comments
Leave a comment