Content

Sunday, April 15, 2018

686 - Goldbach's Conjecture (II)

Problem Link

For any integer n (n ≥ 4) there exist two prime numbers p1 and p2 such that p1 + p2 = n. In a problem we might need to find the number of essentially different pairs (p1, p2), satisfying the condition in the conjecture for a given even number n (4 ≤ n ≤ 2 15). (The word ‘essentially’ means that for each pair (p1, p2) we have p1 ≤p2.)
For example, for n = 10 we have two such pairs: 10 = 5 + 5 and 10 = 3 + 7.

Thus my solution in C++ :

  1.  #include<bits/stdc++.h>
  2. using namespace std;
  3. #define MAX 10000000  ///~10^7
  4. bool prime[MAX];
  5. vector <int> p;
  6. void sieve()
  7. {
  8.     memset(prime,0,sizeof(prime));
  9.     prime[0]=prime[1]=1;
  10.     for(int i = 4; i < MAX; i += 2)
  11.     {
  12.         prime[i] = 1;
  13.     }
  14.     for(int i = 3; i*i < MAX; i += 2)
  15.     {
  16.         if(!prime[i])
  17.         {
  18.             for(int j = i*i; j < MAX; j += i)
  19.                 prime[j] = 1; /// not prime
  20.         }
  21.     }
  22.     for(int i = 2; i < MAX; i++)
  23.         if(!prime[i])
  24.             p.push_back(i);
  25. }
  26. int FindSol(int n)
  27. {
  28.     int res = 0;
  29.     for(int i = 2; i <= n/2; i++)
  30.         if(!prime[i] && !prime[n-i])
  31.             res++;
  32.     return res;
  33. }
  34. int main()
  35. {
  36.     int n;
  37.     sieve();
  38.     while(cin>>n && n)
  39.         cout<<FindSol(n)<<endl;
  40.     return 0;
  41. }

No comments:

Post a Comment