LightOJ 1259 偶數分解成質數有多少種情況

Description
Goldbach’s conjecture is one of the oldest unsolved problems in number theory and in all of mathematics. It states:
Every even integer, greater than 2, can be expressed as the sum of two primes [1].
Now your task is to check whether this conjecture holds for integers up to107.
Input
Input starts with an integer T (≤ 300), denoting the number of test cases.
Each case starts with a line containing an integern (4 ≤ n ≤ 107, n is even).
Output
For each case, print the case number and the number of ways you can expressn as sum of two primes. To be more specific, we want to find the number of(a, b) where
1) Both a and b are prime
2) a + b = n
3) a ≤ b
Sample Input
2
6
4
Sample Output
Case 1: 1
Case 2: 1
Source
Problem Setter: Jane Alam Jan

題意:找出給出的每個數 兩個素數相加的不同形式有多少種;
分析:首先是要找出素數,同時還要找出每對素數相加對應的數;

一開始的想法是線性篩素數,同時開大數組存下每個數的答案,然後。。。。。。
在爆掉幾發Memory 之後纔開使想其他方法;
在經歷了若干發 Memrory和T 之後仔細想了想。

首先注意到我們每次線性篩素數時都會用到訪問標記,如果是素數,標記一定是0;
如果不是則爲1,再注意到素數的個數不會超過%10,統計素數大概6萬個,那麼我們每次將給出的數減去每個已知素數 ,在判斷剩下的數是否是素數不就行了嗎?
考慮最壞情況
6*10^4*300
不會T!

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
using namespace std;
const int maxn=10000005;
bool vis[maxn];
int prime[666666];
void is_prime()
{
    int m=sqrt(maxn+0.5);
    memset(vis,false,sizeof(vis));
    vis[1]=true;
    for(int i=2;i<=m;i++)
    {
        if(!vis[i])for(int j=i*i;j<maxn;j+=i)vis[j]=true;
    }
    int s=0;
    for(int i=1;i<maxn;i++)
    {
        if(!vis[i])prime[++s]=i;
    }
}
int main()
{
    int k;
    is_prime();
    cin>>k;
    for(int i=1;i<=k;i++)
    {
        int n,num=0;
        cin>>n;
        for(int i=1;prime[i]<=n/2;i++)
        {
            if(!vis[n-prime[i]])num++;
        }
        printf("Case %d: %d\n",i,num);
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章