您的位置:首页 > Web前端

hdu 4715 Difference Between Primes (二分查找)

2015-08-15 15:29 519 查看
[align=left]Problem Description[/align]
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.

[align=left]Input[/align]
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.

[align=left]Output[/align]
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'.

[align=left]Sample Input[/align]

3
6
10
20

[align=left]Sample Output[/align]

11 5
13 3
23 3

题意:找两个素数相差为N的素数。
先个所有素数打表。然后对每个N进行二分查找。
注意lower_bound二分查找的用法。

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
int zj[5000000];
int ssb[5000000],pn;
void f()
{
int i,j;
memset(zj,0,sizeof(zj));
zj[0]=zj[1]=1;
pn=0;
for (i=2;i<=5000000;i++)
{
if (!zj[i]) {ssb[pn]=i;pn++;}
for (j=0;j<pn;j++)
{
if (i*ssb[j]>5000000) break;
zj[i*ssb[j]]=1;
if (i%ssb[j]==0) break;
}
}
}
int main()
{
int t,n,i,c;
f();
scanf("%d",&t);
while (t--)
{
scanf("%d",&n);
for (i=0;i<pn;i++)
{
c=lower_bound(ssb,ssb+pn,ssb[i]+n)-ssb;
if (ssb[c]==ssb[i]+n)
{
printf("%d %d\n",ssb[c],ssb[i]);
break;
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: