1928: Prime Distance
| Result | TIME Limit | MEMORY Limit | Run Times | AC Times | JUDGE |
|---|---|---|---|---|---|
| 3s | 8192K | 49 | 19 | Standard |
Your program is given 2 numbers: L and U (1<=L<U<=2,147,483,647), and you are to find the two adjacent primes C1 and C2 (L<=C1<C2<=U) that are closest (i.e. C2-C1 is the minimum). If there are other pairs that are the same distance apart, use the first pair. You are also to find the two adjacent primes D1 and D2 (L<=D1<D2<=U) where D1 and D2 are as distant from each other as possible (again choosing the first pair if there is a tie).
Input
Each line of input will contain two positive integers, L and U, with L < U. The difference between L and U will not exceed 1,000,000.Output
For each L and U, the output will either be the statement that there are no adjacent primes (because there are less than two primes between the two given numbers) or a line giving the two pairs of adjacent primes.Sample Input
2 17 14 17
Output for Sample Input
2,3 are closest, 7,11 are most distant. There are no adjacent primes.
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
int is[50000],prime[50000];
int pl=0;
int ans[100010],flag[1000010];
int isprime(int x)
{
double k=sqrt(0.0+x);
for(int i=0;i<pl&&prime[i]<=k;i++)
{
if(x%prime[i]==0) return 0;
}
return 1;
}
int main()
{
for(int i=2;i<50000;i++)
{
if(is[i]==0) prime[pl++]=i;//0表示素数
for(int j=0;j<pl&&i*prime[j]<50000;j++)
{
is[i*prime[j]]=1;
if(i%prime[j]==0) break;
}
}
int s,t;
while(scanf("%d%d",&s,&t)==2)
{
if(s>t) swap(s,t);
if(s==1) s=2;
int f=0;
int num=0;
int minl,minr,maxl,maxr;
int minc=(1<<31)-1,maxn=(1<<31);
if(t<50000)
{
for(int i=s;i<=t;i++)
{
if(is[i]==0) ans[num++]=i;
}
}
else
{
memset(flag,0,sizeof(flag));//0表示素数
int end=t-s;
// for(int i=s%2;i<=end;i++,i++) flag[i]=1;
for(int i=0;i<pl;i++)
{
int begin=s/prime[i]*prime[i];
if(begin<s) begin+=prime[i];
begin-=s;
for(int j=begin;j<=end;j+=prime[i]) flag[j]=1;
}
for(int i=0;i<=end;i++)
{
if(flag[i]==0) ans[num++]=i+s;
}
}
if(num<2) {printf("There are no adjacent primes./n");continue;}
for(int i=1;i<num;i++)
{
if(ans[i]-ans[i-1]>maxn) maxn=ans[i]-ans[i-1],maxl=ans[i-1],maxr=ans[i];
if(ans[i]-ans[i-1]<minc) minc=ans[i]-ans[i-1],minl=ans[i-1],minr=ans[i];
}
printf("%d,%d are closest, %d,%d are most distant./n",minl,minr,maxl,maxr);
}
return 0;
}
探讨如何通过编程找出指定范围内距离最近及最远的相邻质数对,包括算法设计与实现细节。
297

被折叠的 条评论
为什么被折叠?



