hdoj1397 素数筛选

题目描述:

Problem Description
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.
Input
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.
Output
Each output line should contain an integer number. No other characters should appear in the output.
Sample Input
6
10
12
0
Sample Output
1
2
1

题意:

输入一个数,使两个素数p1和p2之和等于这个数。p1 + p2 = n 和p2 + p1 = n算一对组合,问一共有多少对组合。

此题肯定要用素数筛选,而在求组合的对数时,直接求多半会超时(n最大可取2的15次方)。而通过此题可以看出,实际上我们只需取一半来循环就可以了,因为其中有重复(比如:5 + 7 = 12 和 7 + 5 = 12)。
为了减少运行时间,此题可以先打表。

参考代码:

#include 
#include 
using namespace std;
int primes[32770];
int prime(int num) {
    int flag = 1;
    if (num == 1) {
        return 0;
    }
    for (int k = 2;k * k <= num;++k) {
        if (num % k == 0) {
            flag = 0;
            break;
        }
    }
    return flag;
}
void lastest_prime() {
    for (int num = 2;num <= 32768;++num) {
        int flag = prime(num);
        if (flag) {
            primes[num] = 1;
        }
        else {
            primes[num] = 0;
        }
    }
}
int main() {
    int p;
    int res;
    lastest_prime();
    while (cin >> p && p) {
        int i;
        res = 0;
        for (i = 0;i <= p / 2;++i) {
            if (primes[i] && primes[p-i]) {
                res++;
            }
        }
        cout << res << endl;
    }
    return 0;
}

你可能感兴趣的:(hdoj1397 素数筛选)