Wednesday, June 14, 2017

uva problem solution 543 - Goldbach's Conjecture

problem link:

Discuss:   In this problem you can generate all prime.then compare the smallest problem if it is prime then subtract it from number then compare it with prime number if it is prime number then print both of them or if it is not then increase the value of i;

try yourself before see the code.


#include<bits/stdc++.h>
using namespace std;
int prime(int n)
{
    int i,j,p,d,r,s;
    bool ara[n+1];
    memset(ara,true,sizeof(ara));
     for(i=2;i<=sqrt(n);i++)
     {
         if(ara[i]==true)
         {
             for(j=i*2;j<=n;j+=i)
                ara[j]=false;
         }
     }
     for(i=2;i<=n;i++)
     {
         if(ara[i]==true)
         {
             d=n-i;
             if(ara[d]==true)
             {
                 cout <<n<<' '<<'='<<' '<<i<<' '<<'+'<<' '<<d<<endl;
                 break;
             }
         }
     }
}
int main()
{
    int i,j,n;
    while(cin >>n)
    {
        if(n==0)
            break;
        prime(n);
    }
    return 0;
}

No comments:

Post a Comment