Given with an array of elements and the task is to print those numbers whose digit sum is also prime and return -1 is not such digit exists in an array
Input: arr[]={2,4,3,19,25,6,11,12,18,7}
Output : 2, 3, 25, 11, 12, 7Here, the given output is generated as it contains those additive numbers whose sum is also prime like − 2, 3, 7 are prime but 25(2+5=7), 11(1+1=2), 12(1+2=3) are also prime whereas numbers like 19(1+9=10) are not prime.
Algorithm
START Step 1 -> Take array of int with values Step 2 -> declare start variables as i, m, flag, flag1, sum, r, d, j, tem Step 3 -> store size of array in m as sizeof(arr)/sizeof(arr[0]) Step 4 -> Loop For i=1 and i<m and i++ Set flag=flag1=sum=0 Set d=int(arr[i]/2 Loop For j=2 and j<=d and j++ IF arr[i]%j==0 Set flag=1 Break End IF End IF flag=0 Set tem=arr[i] Loop While tem Set r=tem%10 Set sum=sum+r Set tem=tem/10 End Set d=int(sum/2) Loop For j=2 and j<=d and j++ IF sum%j=0 Set flag1=1 break End End IF flag1=0 Print arr[i] End End End STOP
Example
#include<iostream>
using namespace std;
int main(){
int arr[]={2,4,3,19,25,6,11,12,18,7};
int i,m,flag,flag1,sum,r,d,j,tem;
m=sizeof(arr)/sizeof(arr[0]);
for(i=0;i<m;i++) {
flag=flag1=sum=0;
d=int(arr[i]/2);
for(j=2;j<=d;j++){
if(arr[i]%j==0) {
flag=1;
break;
}
}
if(flag==0) {
tem=arr[i];
while(tem) {
r=tem%10;
sum=sum+r;
tem=tem/10;
}
d=int(sum/2);
for(j=2;j<=d;j++) {
if(sum%j==0){
flag1=1;
break;
}
}
if(flag1==0){
cout<<arr[i]<<" ";
}
}
}
}Output
if we run the above program then it will generate the following output
2 3 11 25 12 7