此题就是给定两个数,让你求出在这之间两个相邻素数的最远距离和最近距离!!
思路:先打出一个素数表,在进行查找遍历。
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <vector>
#include <queue>
#include <cstdio>
#include <cmath>
#include <string>
#include <stack>
#define maxn 1000001
#define maxn 1000001
using namespace std;
long long ptmp[50000],plist[50000],pcount=0;
long long map[maxn],map1[maxn],kk=0;
void initprime() {
memset(ptmp,0,sizeof(ptmp));
for(int i=2; i<47000; i++) {
if(0==ptmp[i]) {
plist[pcount++]=i;
for(int k=i*2; k<=47000; k+=i)
ptmp[k]=1;
}
}
}
int main() {
long long a,b;
initprime();
while(cin>>a>>b) {
kk=0;
if(a==1)
a++;
memset(map,0,sizeof(map));
for(long long i=0; i<pcount&&plist[i]*plist[i]<=b; i++) {
long long tmp1=a/plist[i];
if(tmp1*plist[i]!=a)
tmp1++;
if(tmp1==1)
tmp1++;
for(long long j=tmp1*plist[i]; j<=b; j+=plist[i])
map[j-a]=1;
}
for(long long i=a; i<=b; i++) {
if(map[i-a]==0)
map1[kk++]=i;
}
if(kk<2)
cout<<"There are no adjacent primes."<<endl;
else {
long long m1=map1[0],m2=map1[1],n1=map1[0],n2=map1[1];
for(int i=2; i<kk; i++) {
if(map1[i]-map1[i-1]<m2-m1)
m2=map1[i],m1=map1[i-1];
if(map1[i]-map1[i-1]>n2-n1)
n2=map1[i],n1=map1[i-1];
}
cout<<m1<<","<<m2<<" are closest, "<<n1<<","<<n2<<" are most distant."<<endl;
}
}
return 0;
}