LightOJ 1259 Goldbach`s Conjecture 素数打表

题目大意:求讲一个整数n分解为两个素数的方案数。

题目思路:素数打表,后遍历 1-n/2,寻找方案数,需要注意的是:C/C++中 bool类型占用一个字节,int类型占用4个字节,在素数打表中采用bool类型可以节约不少内存。

 

#include<iostream>
#include<algorithm>
#include<cstring>
#include<vector>
#include<stdio.h>
#include<queue>
#include<math.h>
#define INF 0x3f3f3f3f
#define MAX 10000005
#define Temp 10000005

using namespace std;

int p[664589],cnt=0;
bool vis[MAX];

void GetPrime()//素数打表
{
    memset(vis,false,sizeof(vis));
    memset(p,0,sizeof(p));
    for(int i=2;i<MAX;i++)
    {
        if(!vis[i])
        {
            p[++cnt]=i;
            for(int j=i+i;j<MAX;j+=i)
            {
                vis[j]=true;
            }
        }
    }
}

int main()
{
    GetPrime();
    int n,T,sum,cns=0;
    scanf("%d",&T);
    while(T--)
    {
        sum=0;
        scanf("%d",&n);
        for(int i=1;p[i]<=n/2;i++)//遍历寻找方案数
        {
            if(vis[n-p[i]]==false)
                sum++;
        }
        printf("Case %d: %d\n",++cns,sum);
    }
    return 0;
}
View Code

 

posted @ 2016-09-26 13:16  声声醉如兰  阅读(136)  评论(0编辑  收藏  举报