您的位置:首页 > 其它

sgu231:Prime Sum(简单数学题)

2015-05-23 17:20 134 查看
题目大意:

~~~~~~求出1⋯n1\cdots n之内所有的质数对,满足它们的和≤n\leq n且和为质数。

分析:

~~~~~~如果是两奇质数相加,和为偶数,肯定不是质数。

~~~~~~所以只能是2+prime2+prime的形式,然后欧拉筛枚举即可。

AC code:

[code]#include <cstdio>
#include <vector>
#define pb push_back
#define mp make_pair
#define ONLINE_JUDGE
typedef long long LL;
using namespace std;

const int MAXN = 1e6+9;

int n;
int prime[MAXN/5], tot;
bool hash[MAXN];
vector< pair<int,int> > ans;

void euler(int n)
{
    for(int i = 2; i <= n; ++i)
    {
        if(!hash[i]) prime[++tot] = i;
        for(int j = 1; j <= tot && (LL)i*prime[j] <= n; ++j)
        {
            hash[i*prime[j]] = true;
            if(i%prime[j] == 0) break;
        }
    }
}

int main()
{
    #ifndef ONLINE_JUDGE
    freopen("sgu231.in", "r", stdin);
    freopen("sgu231.out", "w", stdout);
    #endif

    scanf("%d", &n);
    euler(n);
    for(int i = 1; i <= tot && 2+prime[i] <= n; ++i)
        if(!hash[2+prime[i]])
            ans.pb(mp(2, prime[i]));
    printf("%d\n", ans.size());
    for(int i = 0, sz = ans.size(); i < sz; ++i)
        printf("%d %d\n", ans[i].first, ans[i].second);

    #ifndef ONLINE_JUDGE
    fclose(stdin);
    fclose(stdout);
    #endif
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: