Given an integer n (between 1 and 104) find two prime numbers (possibly same) p1,p2 such that p1+p2=n
In case there are multiple solutions, you can output any of them.
If there is no solution, then print -1 -1 instead.
using namespace std;
/*
Given an integer n (between 1 and 104) find two prime numbers (possibly same) p1,p2 such that p1+p2=n
In case there are multiple solutions, you can output any of them.
If there is no solution, then print -1 -1 instead.
*/
#define MAX 50
int is_prime(int n)
{
int i, Flag = 1;
if (n == 0 || n == 1) Flag=0;
else
{
for(i = 2; i <= n/2; ++i)
{
if(n % i == 0) Flag = 0;
}
}
return (Flag);
}
int main()
{
int n=0,Prime[MAX],m=50,c=0,r,u=-1,v=-1,Flag=0;
m=0;
while(m<1 || m>104)
{
cout<<"\nEnter a number between 1 and 104: "; cin>>m;
}
for(n=0;n<MAX;n++)Prime[n] = 0;
for(n=1;n<104;n++)
{
if(is_prime(n)==1) {Prime[c] = n;c++;}
}
for(n=0;n<c;n++)
{
for(r=0;r<c;r++)
{
if(Prime[r]+Prime[c]==m)
{
Flag=1;
u=Prime[r]; v = Prime[c];
cout<<"\nPairs: "<<u<<", "<<v<<endl;
}
}
}
if(Flag==0) cout<<"\n\t-1 -1";
return(0);
}
Comments
Leave a comment