hdu 4715 Difference Between Primes【筛法快速求素数表+思维】

来源:互联网 发布:手游代练软件 编辑:程序博客网 时间:2024/05/01 04:58

Difference Between Primes

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 3215    Accepted Submission(s): 913


Problem Description
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<10^5). There is a even number xat the next nlines. The absolute value of xis not greater than 10^6.
 

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

Source
2013 ACM/ICPC Asia Regional Online —— Warmup
 
 题目大意:
给你一个偶数n,让你求出两个素数,使得这两个素数相减等于n,输出要保证这两个素数是最小的组合。
思路:
首先我们确定一下总体的思路,我们既然是要找两个素数,最直接能够想到的就是两层for枚举i,j,使得i-j==n即输出,但是因为n比较大,所以导致两层for的i,j也是要比较大, 10^6*10^6是一定会超时的,这个思路基本上现在是可以pass了,这个时候我们可以想想如何改变式子来达到优化算法。
我们要找i-j==n,n是已知的,从两个未知找一个已知。我们不如让n,j位子互换变成:i-n==j,辣么我们就相当于一个未知一个已知找一个未知,但是这个未知其实我们相当于知道了,因为我们这个时候只需要判断一下j是否是素数即可。
辣么就会节省好多好多好多好多好多时间。
另外这样确定了之后直接敲然后直接交是会WA的。因为数据范围给的是:数据不会大于10^6,辣么-4也是属于可行范围啊。所以我们还需要判断一下负数的问题。把整个思路都敲定了之后,我们就可以一发AC辣~
AC代码:

#include<stdio.h>#include<string.h>#include<math.h>#include<iostream>using namespace std;int Is_or[1500000];void init(){    memset(Is_or,0,sizeof(Is_or));    Is_or[0]=1;    Is_or[1]=1;    int a,b;    for(int j=2;j<sqrt(1500000);j++)    {        if(Is_or[j]==0)        for(int k=j+j;k<=1500000;k+=j)        {            Is_or[k]=1;        }    }}int main(){    init();    int t;    scanf("%d",&t);    while(t--)    {        int n,flag=0;        scanf("%d",&n);        int ans1,ans2;        if(n<0) {flag=1,n=-n;}        int ok=0;        for(int i=n;i<1500000;i++)        {            if(Is_or[i]==0)            {                if(Is_or[i-n]==0)                {                    ok=1;                    ans1=i;                    ans2=i-n;                    break;                }            }        }        if(ok==1)          if(!flag) printf("%d %d\n",ans1,ans2);          else printf("%d %d\n",ans2,ans1);        else printf("FAIL\n");    }}











0 0
原创粉丝点击