POJ2262 - Goldbach's Conjecture

首先生成1000000以内的素数表,采用素数筛选法http://www.cnblogs.com/bournet/p/3972023.html。下面就很简单了。

 1 #include <iostream>
 2 #include <math.h>
 3 using namespace std;
 4 
 5 int main()
 6 {
 7     int N = 1000000;
 8     bool prime[N+1];
 9     for (int i = 0; i < N; i++)
10     {
11         if (i%2 == 0 && i != 2)
12             prime[i] = false;
13         else
14             prime[i] = true;
15     }
16 
17     for (int i = 3; i <= sqrt(N); i += 2)
18     {
19         if (prime[i])
20             for (int j = i+i; j <= N; j += i)
21                 prime[j] = false;
22     }
23 
24     int n;
25     while (cin >> n)
26     {
27         if (n == 0)
28             return 0;
29         for (int i = 2; i <= n/2; i++)
30         {
31             if (prime[i])
32             {
33                 if (prime[n-i])
34                 {
35                     cout << n << " = " << i << " + " << n-i << endl;
36                     break;
37                 }
38             }
39             if (i == n/2)
40             {
41                 cout << "Goldbach's conjecture is wrong." << endl;
42             }
43         }
44     }
45 
46     return 0;
47 }

 

posted @ 2014-09-15 20:54  bournet  阅读(111)  评论(0编辑  收藏  举报