POJ 2909 Goldbach's Conjecture(我的水题之路——任一数为素数对之和)

Goldbach's Conjecture
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 8369   Accepted: 4843

Description

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. There can be many such numbers. 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 (p1p2) and (p2p1) 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 215. 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

Source

Svenskt Mästerskap i Programmering/Norgesmesterskapet 2002

问,一个大于等于4的数,可以由多少对素数相加求和得到。

先是筛法求出素数表,然后对于每次得到的数字n,与第i个素数相减,求到的差查询是否为素数,如果是,则次数加一,不是就进行下一个素数求差。

注意点:
1)需要比较次数的素数仅有小于n/2的即可
2)如果n是奇数,可以直接输出1.因为两个数之和为奇数的仅有奇偶相加,而偶数素数只有2一个。(AC验证)

代码(2AC):
#include <cstdio>
#include <cstdlib>
#include <cstring>

#define N 40000

int prime[N];
int primes[N];

int init(){
    int i, j, k;

    for (i = 0; i < N; i++){
        prime[i] = 1;
    }
    prime[0] = 0;
    prime[1] = 0;
    for (i = 2; i < N; i++){
        if (prime[i] != 0){
            for (j = i + i; j < N; j += i){
                prime[j] = 0;
            }
        }
    }
    for (i = j = 0, k = 1; i < N; i++){
        if (prime[i] != 0){
            prime[i] = k++;
            primes[j++] = i;
        }
    }
    return k - 1;
}

int main(void){
    int n, prinum;
    int i, j;
    int tmp, times;

    prinum = init();
    while (scanf("%d", &n), n != 0){
        if (n % 2 == 0){
            for (times = i = 0; primes[i] <= n / 2 && i < prinum; i++){
                tmp = n - primes[i];
                if (prime[tmp] != 0){
                    times ++;
                }
            }
        }
        else{
            times = 1;
        }
        printf("%d\n", times);
    }
    return 0;
}


你可能感兴趣的:(POJ 2909 Goldbach's Conjecture(我的水题之路——任一数为素数对之和))