http://poj.org/problem?id=2689
/* 区间筛法适用于L, R范围比较大,但是区间长度较小时 套个模板然后取出最小最大就可以 */ /************************************************ * Author :Powatr * Created Time :2015-8-17 9:38:50 * File Name :POJ2689.cpp ************************************************/ #include <cstdio> #include <algorithm> #include <iostream> #include <sstream> #include <cstring> #include <cmath> #include <string> #include <vector> #include <queue> #include <deque> #include <stack> #include <list> #include <map> #include <set> #include <bitset> #include <cstdlib> #include <ctime> using namespace std; #define lson l, mid, rt << 1 #define rson mid + 1, r, rt << 1 | 1 typedef long long ll; const int MAXN = 1e6 + 1e4; const int INF = 0x3f3f3f3f; const int MOD = 1e9 + 7; const int N = 50010; bool prime[MAXN]; bool sieve[N]; int len; void segent_sieve(ll L, ll R) { len = R - L + 1; for(int i = 0; i < len; i++) prime[i] = true; if(1 - L >= 0) prime[1-L] = false;//特判 for(ll i = 2; i*i < R; i++){ if(seive[i]){ for(ll j = max(1ll*2, (L-1+i)/i)*i; j <= R; j+=i)//(L-1+i/i)得到最接近L的i的倍数 prime[j-L] = false; //偏移量,因为单纯j会导致数组越界,把范围弄到0到len上 } } } int main(){ //艾氏筛法 O(nlognlogn) for(int i = 2; i < N; i++) sieve[i] = true; for(int i = 2; i*i < N; i++){ if(sieve[i]){ for(int j = i*2; j < N; j+=i){ sieve[j] = false; } } } int L, R; while(~scanf("%d%d", &L, &R)){ segent_seive(L, R); int mmax, mmin; int lmax, rmax, lmin, rmin; mmax = -1, mmin = 1 << 30; int t = -1; for(int i = 0; i < len; i++){ if(prime[i]){ if(t >= 0){ if(mmax < i - t) mmax = i - t, lmax = L + t, rmax = L + i; if(mmin > i - t) mmin = i - t, lmin = L + t, rmin = L + i; t = i; } else t = i; } } if(mmax != -1 || mmin != 1 << 30) printf("%d,%d are closest, %d,%d are most distant. ", lmin, rmin, lmax, rmax); else printf("There are no adjacent primes. "); } return 0; }