POJ2909 Goldbach's Conjecture

Goldbach's Conjecture
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 10708   Accepted: 6301

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

题目大意:对于给的数n(4<=n<=2^15),p1+p2=n,但是p1和p2都是素数,写出程序求对于n总共有多少对这样的数。


思路:开一个2^15的bool型数组,以下标为值,如果值为素数这里标记为true;然后从n开始递归,依次减一,知道n小于n/2。这样避免了相同的p1、p2出现.

代码如下

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#define MAXN 32769
using namespace std;

bool isp[MAXN];   //标记此点是否为素数
int N,ans;

inline int is_prime(int n)   //素数判断
{
    if(n<=1) return 0;
    int m=floor(sqrt(n)+0.5);
    for(int i=2;i<=m;i++)
        if(n%i==0) return 0;
    return 1;
}

void init()   //对数组进行初始化
{
    memset(isp,0,sizeof(isp));
    isp[0]=false;
    for(int i=1;i<=MAXN;i++)
    {
        if(is_prime(i)) isp[i]=true;
    }
}

void dfs(int n)   //开始递归求解
{
    if(n<(N/2)) return; //如果递归到n/2,就不用递归了,
    if(isp[n] && isp[N-n] ) ans++;
    dfs(n-1);
}

int main()
{
    init();
    while(scanf("%d",&N) && N)
    {
        ans=0;
        int n;
        n=N;
        dfs(n);
        printf("%d\n",ans);
    }
	return 0;
}

你可能感兴趣的:(DFS)