Solution to Given an integer n (between 1 and 104) find two prime numbers (possibly same) p1,p2 … - Sikademy
Author Image

Archangel Macsika

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.

The Answer to the Question
is below this banner.

Can't find a solution anywhere?

NEED A FAST ANSWER TO ANY QUESTION OR ASSIGNMENT?

Get the Answers Now!

You will get a detailed answer to your question or assignment in the shortest time possible.

Here's the Solution to this Question

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);

}

Related Answers

Was this answer helpful?

Join our Community to stay in the know

Get updates for similar and other helpful Answers

Question ID: mtid-3-stid-44-sqid-1007-qpid-4