SDNUOJ-1500-哥德巴赫猜想-素数-二分
题目
Description Spring is coming, T_T. All you know Goldbach conjecture.That is to say, Every even integer greater than 2 can be expressed as the sum of two primes. Today, skywind present a new conjecture: every even integer can be expressed as the difference of two primes. To validate this conjecture, you are asked to write a program. Input The first line of input is a number n identified the count of test cases(n<10^4). There is a even number x at the next n lines. The absolute value of x is not greater than 10^6. Output For each number x tested, outputs two primes a and b at one line separated with one space where a-b=x. If more than one group can meet it, output the minimum group(of course refers b). If no primes can satisfy it, output 'FAIL'.
样例
Sample Input 3 6 10 20 Sample Output 11 5 13 3 23 3
题目分析
题意
验证哥德巴赫猜想,任一大于2的偶数都可写成两个质数之和。给出一个数N,求满足N = 素数A - 素数B的结果。结果会有很多,因此要求B最小的结果。
思路
N = 素数A - 素数B
移项,可得:
N + 素数B = 素数A (求B最小的情况)
因此可以利用素数筛打表,然后从最小的素数跑暴力。
即:判断 N + 素数B 是否为素数,可以在之前打的素数表中进行二分查找,如果能找到,则说明结果正确。
代码
#include <iostream>
#include <cstdio>
using namespace std;
const int TOP = 1e6 + 100000;
bool e[TOP];
int p[TOP / 5];
int pnum;
void init() {
e[0] = e[1] = 1;
pnum = 0;
for (int i = 2; i < TOP; i++) {
if (e[i] == 0)p[++pnum] = i;
for (int j = 1; j <= pnum && p[j] * i < TOP; j++) {
e[p[j] * i] = 1;
if (i % p[j] == 0)break;
}
}
}
bool binSearch(int n) {
int l = 1;
int r = pnum - 1;
int mid = (l + r) / 2;
while (l != mid) {
mid = (l + r) / 2;
if (p[mid] == n) {
return true;
} else if (p[mid] > n) {
r = mid;
} else {
l = mid;
}
mid = (l + r) / 2;
}
return false;
}
int main() {
init();
int T, tmp;
scanf("%d", &T);
while (T--) {
scanf("%d", &tmp);
if (tmp == 0) {
printf("2 2\n");
continue;
}
for (int i = 1; i < pnum; i++) {
if (binSearch(p[i] + tmp)) {
printf("%d %d\n", p[i] + tmp, p[i]);
break;
}
}
}
return 0;
}</cstdio></iostream>
Code language: PHP (php)