HUSTOJ 2125: Goldbach's Conjecture

题目描述

Goldbach’s Conjecture: For any even number n greater than or equal to 4, there exists at least one pair of prime numbers p1 and p2 such that n = p1 + p2.
This conjecture has not been proved nor refused yet. No one is sure whether this conjecture actually holds. However, one can find such a pair of prime numbers, if any, for a given even number. The problem here is to write a program that reports the number of all the pairs of prime numbers satisfying the condition in the conjecture for a given even number.

A sequence of even numbers is given as input. Corresponding to each number, the program should output the number of pairs mentioned above. Notice that we are interested in the number of essentially different pairs and therefore you should not count (p1, p2) and (p2, p1) separately as two different pairs.

输入

An integer is given in each input line. You may assume that each integer is even, and is greater than or equal to 4 and less than 2^15. The end of the input is indicated by a number 0.

输出

Each output line should contain an integer number. No other characters should appear in the output.

样例输入

4
10
16
0

样例输出

1
2
2

解题思路

  1. 获取素数使用素数筛法,见HUSTOJ 1945
  2. 最大素数prime[maxn-1]需要大于2^16(1<<16),同样maxn可以先设置一个较大的数,将prime[maxn-1]和1<<16比较
  3. prime[maxn]数组为有序素数组,寻找任意两个元素之和等于K可以采用two points(数组游标)方法

AC代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include<iostream>
using namespace std;

const int maxn=1<<17;
int pnum=0;
int p[maxn]={0};
int prime[maxn]={0};

void findprime()
{
for(int i=2; i<maxn; i++)
{
if(!p[i])
prime[pnum++]=i;
for(int j=i+i; j<maxn; j=j+i)
{
p[j]=1;
}
}
}

int main()
{
int n=0;
findprime();
while(cin>>n)
{
if(!n)
{
break;
}
int i=0; // two points
int j=n;
int cnt=0;
while(i<=j)
{
if(prime[i]+prime[j]==n)
{
cnt++;
i++;
j--;
}
else if(prime[i]+prime[j]>n)
{
j--;
}
else if(prime[i]+prime[j]<n)
{
i++;
}
}
cout<<cnt<<endl;
}
return 0;
}
分享到: