POJ 2909 Goldbach's Conjecture (求x=p1+p2)

题意:哥德巴赫猜想。任意一个>=4的偶数可以写成两个素数之和。即x=p1+p2。给出一个x,求p1,p2的对数。

#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;

#define MAX 32768
int p[MAX], a[MAX], pn;

void prime ()
{
    int i, j; pn = 0;
    memset(a,0,sizeof(a));
    for ( i = 2; i < MAX; i++ )
    {
        if ( !a[i] ) p[pn++] = i;
        for ( j = 0; j < pn && i * p[j] < MAX && (p[j] <= a[i] || a[i] == 0); j++ )
            a[i*p[j]] = p[j];
    }
}

int count ( int x )
{
    int cnt = 0;
    for ( int i = 0; i < pn && p[i] < x; i++ )
    {
        if ( p[i] <= x - p[i] && !a[x-p[i]] ) cnt++;
        if ( p[i] > x - p[i] ) break;
    }
    return cnt;
}

int main()
{
    prime();
    int x;
    while ( scanf("%d",&x) && x )
        printf("%d\n",count(x));
    return 0;
}



你可能感兴趣的:(POJ 2909 Goldbach's Conjecture (求x=p1+p2))