Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- #define MAX 100000
- #define ll long long
- using namespace std;
- vector<long long int> smallprimes;
- void sieve() {
- bool isPrime[MAX];
- for (ll i = 0; i < MAX; i++) isPrime[i] = true;
- for (ll i = 3; i * i <= MAX; i += 2)
- if (isPrime[i])
- for (ll j = i * i; j < MAX; j += i)
- isPrime[j] = false;
- smallprimes.push_back(2);
- for (ll i = 3; i < MAX; i += 2)
- if (isPrime[i]) smallprimes.push_back(i);
- }
- void segSieve (ll lower,ll upper) {
- bool isPrime[1000010];
- for (ll i = 0; i <= upper - lower ; i++) isPrime[i] = true;
- if (lower == 1) isPrime[0] = false;
- for (ll i = 0; smallprimes[i]*smallprimes[i] <= upper; i++) {
- ll cur = smallprimes[i];
- ll base = (lower/cur)*cur;
- if (base < lower) base += cur;
- for (ll j = base; j <= upper; j += cur)
- isPrime[j-lower] = false;
- if (base == cur) isPrime[base-lower] = true;
- }
- ll dif,min_dif=1000010,max_dif=0,mnv1,mnv2,mxv1,mxv2,curitem;
- bool check=true;
- //for (ll int i=0;i<upper-lower-1;i++)
- //{2111111207,2111111209 are closest, 2111111213,2111111291 are most distant.
- // if(isPrime[i]) cout<<i+lower<<endl;
- //}
- for (ll i = 0; i < upper - lower + 1; i++) {
- if ( check && isPrime[i]){
- curitem=i+lower;
- //cout<<"First curitem = "<<curitem<<endl;
- check=false;
- continue;
- }
- if (isPrime[i]){
- dif=(i+lower)-curitem;
- //cout<<"Curitem = "<<curitem<<" Dif = "<<dif<<endl;
- if (dif>max_dif){
- max_dif=dif;
- mxv1=curitem;
- mxv2=i+lower;
- }
- if (dif<min_dif){
- min_dif=dif;
- mnv1=curitem;
- mnv2=i+lower;
- }
- curitem=i+lower;
- }
- }
- if (max_dif==0) cout<<"There are no adjacent primes."<<endl;
- else cout<<mnv1<<","<<mnv2<<" are closest, "<<mxv1<<","<<mxv2<<" are most distant."<<endl;
- }
- int main() {
- sieve();
- ll int l, u;
- while(cin>>l>>u) {
- segSieve(l,u);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement