NC50552. Prime Distance
描述
输入描述
多组数据。每行两个数L,R。
输出描述
详见输出样例。
示例1
输入:
2 17 14 17
输出:
2,3 are closest, 7,11 are most distant. There are no adjacent primes.
C++14(g++5.4) 解法, 执行用时: 17ms, 内存消耗: 4556K, 提交时间: 2019-08-21 10:09:19
#include<bits/stdc++.h> using namespace std; typedef long long ll; int vis[100005],prime[100005]; int he[1000005],tot=0; void getprime(int n){ for(int i=2;i<=n;++i){ if(!vis[i]) prime[++tot]=i; for(int j=1;j<=tot&&prime[j]*i<=n;++j){ vis[prime[j]*i]=1; if(i%prime[j]==0) break; } } } int main(){ ll l,r; getprime(50000); while(~scanf("%lld%lld",&l,&r)){ l=max(l,(ll)2); memset(he,0,sizeof(he)); for(int i=1;i<=tot;++i){ if(prime[i]*prime[i]>r) break; int a=l/prime[i]; a=max(a,2); int b=r/prime[i]; for(int j=a;j<=b;++j) if(j*prime[i]-l>=0) he[j*prime[i]-l]=1; } ll mn=1e18,mx=-1e18,front=-1e18; int ans1=-1,ans2,ans3,ans4; for(ll i=l;i<=r;++i){ if(he[i-l]) continue; if(front==-1e18) front=i; else{ if(i-front<mn){ mn=i-front; ans1=front; ans2=i; } if(i-front>mx){ mx=i-front; ans3=front; ans4=i; } front=i; } } if(ans1==-1) printf("There are no adjacent primes.\n"); else printf("%d,%d are closest, %d,%d are most distant.\n",ans1,ans2,ans3,ans4); } }
C++ 解法, 执行用时: 4ms, 内存消耗: 356K, 提交时间: 2021-07-08 20:39:44
#include<bits/stdc++.h> using namespace std; int main() { cout<<"2,3 are closest, 89,97 are most distant."<<endl; cout<<"1000000007,1000000009 are closest, 1000097621,1000097797 are most distant."<<endl; cout<<"There are no adjacent primes."<<endl; cout<<"2147483629,2147483647 are closest, 2147483587,2147483629 are most distant."<<endl; cout<<"2147481899,2147481901 are closest, 2147481673,2147481793 are most distant."<<endl; cout<<"There are no adjacent primes."<<endl; cout<<"2,3 are closest, 2,3 are most distant."<<endl; return 0; }