POJ - 2689 Prime Distance

POJ - 2689 Prime Distance

 

代码:

POJ - 2689 Prime Distance
#include<iostream>
#include<map>
#include<vector>
#include<algorithm>
using namespace std;
#define int long long
#define debug(a) cout << #a << ' ' << a << '\n';
#define debug2(a , b) cout << #a << ' ' << a << " | " << #b << ' ' << b << '\n';
#define cn cout << '\n';
#define INF 1e18
#define pb push_back 
const int maxn = 1e7 + 10;
const int mod = 1e9 + 7;
int prime[maxn];
bool isprime[maxn];
int cnt = 0;
int vis[maxn];
vector<int>vec;
signed main()
{
    //ios::sync_with_stdio(false);
    //cin.tie(0);
    //cout.tie(0);
    for(int i = 2 ; i <= 1e6 ; i ++) isprime[i] = true;
    for(int i = 2 ; i <= 1e6 ; i ++){
        if(isprime[i])prime[cnt ++] = i;
        for(int j = 2 ; j * i <= 1e6 ; j ++){
            isprime[i * j] = false;
        }
    }
    int L , R;
    while(cin >> L >> R){
        int c1 = -1 , c2 = -1 , d1 = -1 , d2 = -1 , maxx = 0 , minn = 1e18;
        for(int i = 0 ; i < 1e6 ; i ++)vis[i] = 0; 
        for(int i = 0 ; i < cnt ; i ++){
        //    if(prime[i] * prime[i] > R)break;
            int l = max(2ll , L / prime[i]);
            for(int j = l * prime[i] ; j <= R ; j += prime[i]){
                if(j < L) continue;
                vis[j - L] ++;
            }
        }
        vec.clear();
        if(L == 1) vis[0] = 1;
        for(int i = L ; i <= R ; i ++){
            if(vis[i - L] == 0){
                vec.pb(i);
            }
        }
        for(int i = 1 ; i < vec.size() ; i ++){
            if(vec[i] - vec[i - 1] < minn){
                minn = vec[i] - vec[i - 1];
                d1 = i - 1 , d2 = i;
            }
            if(vec[i] - vec[i - 1] > maxx){
                maxx = vec[i] - vec[i - 1];
                c1 = i - 1 , c2 = i;
            }
        }
        if(vec.size() <= 1){
            cout << "There are no adjacent primes.\n";
        }
        else{
            cout << vec[d1] << ',' << vec[d2] << " are closest, " << vec[c1] << ',' << vec[c2] << " are most distant.\n";
        }
    }
    return 0;
}
View Code

 

上一篇:2945:拦截导弹


下一篇:百年孤独