Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 15901 | Accepted: 4227 |
Description
Input
Output
Sample Input
2 17 14 17
Sample Output
2,3 are closest, 7,11 are most distant. There are no adjacent primes.
Source
#include <iostream> #include <cstdio> #include <cstring> #include <vector> #include <queue> #include <algorithm> #define MAXN 1000005 #define INF 0xfffffff using namespace std; typedef long long ll; bool is_prime[MAXN]; bool is_prime_small[MAXN]; ll a,b; void segment_sieve()//筛选a~b区间内的素数,is_prime[i-a]=true时,i是素数 { for(ll i=0; i*i<=b; ++i) is_prime_small[i]=true; for(ll i=0; i<=b-a; ++i) is_prime[i]=true; for(ll i=2; i*i<=b; ++i) { if(is_prime_small[i]) { for(ll j=2*i; j*j<=b; j+=i) is_prime_small[j]=false;//2~sqrt(b) for(ll j=max(2LL,(a+i-1)/i)*i; j<=b; j+=i) is_prime[j-a]=false;//a~b } } } ll cnt,prime[MAXN];//a~b区间内素数的个数和素数表 void getnum() { for(ll i=a; i<=b; ++i) if(is_prime[i-a]) if(i!=1) prime[cnt++]=i; //for(ll i=0; i<=cnt; ++i) //cout<<prime[i]<<endl; } int main() { ios::sync_with_stdio(false); cin.tie(0); while(cin>>a>>b) { memset(is_prime,false,sizeof(is_prime)); memset(is_prime_small,false,sizeof(is_prime_small)); memset(prime,0,sizeof(prime)); cnt=0; segment_sieve(); getnum(); ll x=0,xx=0,y=0,yy=0,Max=-1,Min=INF; for(ll i=1; i<cnt; ++i) { if((prime[i]-prime[i-1])<Min) { x=prime[i-1],xx=prime[i]; Min=xx-x; } if((prime[i]-prime[i-1])>Max) { y=prime[i-1],yy=prime[i]; Max=yy-y; } } if(cnt==0||cnt==1) cout<<"There are no adjacent primes."<<endl; else cout<<x<<","<<xx<<" are closest, "<<y<<","<<yy<<" are most distant."<<endl; } return 0; } /* 1 5 2 17 14 17 22 37 22801763 22801787 2147483000 2147483647 */