素数筛总结----基于HDU - 4715(Difference Between Primes)

素数筛模板
void Prime(){
	for(int i=2;2*i<MAX;++i) { prime[2*i]=true; } //任意一个数的两倍都不是素数,于预处理一下。
	for(int i=3;i*i<MAX;i+=2){ //i不考虑是偶数的情况
		if(!prime[i]) {//如果从一开始prime数组就没存i值,则i就是素数
			s[++size]=i; //是素数的保存下来
			for(int j=i*i;j<MAX;j+=i) { prime[j]=true; }//在考虑这个素数的倍数
		}
	}
}
题面

All you know Goldbach conjecture.That is to say, Every even integer greater than 2 can be expressed as the sum of two primes. Today, skywind present a new conjecture: every even integer can be expressed as the difference of two primes. To validate this conjecture, you are asked to write a program.

Input

The first line of input is a number nidentified the count of test cases(n<105). There is a even number xat the next nlines. The absolute value of xis not greater than 106 .

Output

For each number xtested, outputstwo primes aand bat one line separatedwith one space where a-b=x. If more than one group can meet it, output the minimum group. If no primes can satisfy it, output ‘FAIL’.

Sample Input
3
6
10
20
Sample Output
11 5
13 3
23 3
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<string>
#include<queue>
#include<algorithm>
#include<map>
#include<iomanip>
#define INF 99999999
using namespace std;

const int V = 1500000;
bool prime[V];
int ans[200] = {2}, sizes = 1;
void Prime()
{
    prime[0] = true;
    prime[1] = true;

    for(int i=2; i*2<V; i++) prime[i*2] = true;
    for(int i=3; i*i<V; i+=2){
        if(!prime[i]){
            ans[sizes++] = i;
            for(int j=i*2; j<V; j += i) prime[j] = true;
        }
    }
}

int main()
{
    Prime();
    int t, n;
    scanf("%d", &t);
    while(t--){
        scanf("%d", &n);
        int flag = 0, ok = 0;
        if(n < 0) flag = 1, n = -n;
        int i;
        for(i=0; i<sizes; i++){
            if(!prime[ans[i]+n]) { ok = 1; break; }
        }
        if(ok) {
            if(flag) printf("%d %d\n", ans[i], ans[i] + n);
            else printf("%d %d\n", ans[i]+n, ans[i]);
        } else{
            printf("FAIL\n");
        }
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值