poj 2689
A的挺费劲的。。。用筛法求某个区间内的素数。
思路想通的挺快就是实现的真难。。
//============================================================================ // Name : 2689.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include <cstdio> #include <cstring> using namespace std; bool tag[60000], flag[1000010]; long long l, r, Max, Min, t0, pre, t, num; long long prime[1000010]; int main() { freopen("a.txt", "r", stdin); num = 0; tag[1] = true; for(int i = 2;i <= 60000;i++){ if(tag[i] == false){ prime[++num] = i; for(int j = i<<1;j <= 60000;j+=i){ tag[j] = true; } } } while(scanf("%d%d", &l, &r)!=EOF){ if(l == 1) l = 2; memset(flag, false, sizeof(flag)); for(int i = 1;prime[i]*prime[i] <= r;i++){ t = l/prime[i]+(l%prime[i]!=0); if(t == 1) t++; for(long long j = t*prime[i];j <= r;j+=prime[i]){ flag[j-l] = true; } } t0 = 0; Max = 0; Min = 2147483647; for(long long i = l;i <= r;i++){ if(flag[i-l] == false&&t0 == 0){ t0 = 1; pre = i; } else if(flag[i-l] == false&&t0 == 1){ t0 = 2; t = i-pre; if(Max < t) Max = t; if(Min > t) Min = t; pre = i; } else if(flag[i-l] == false){ t = i-pre; if(Max < t) Max = t; if(Min > t) Min = t; pre = i; } } if(t0 != 2){ printf("There are no adjacent primes.\n"); } else{ // printf("%lld, %lld\n", Min, Max); int t1 = 0; for(long long i = l;i <= r;i++){ if(flag[i-l] == false&&t1 == 0){ t1 = 1; pre = i; } else if(flag[i-l] == false&&t1 == 1){ t1 = 2; t = i-pre; if(t == Min){ printf("%lld,%lld are closest, ", pre, i); break; } pre = i; } else if(flag[i-l] == false){ t = i-pre; if(t == Min){ printf("%lld,%lld are closest, ", pre, i); break; }pre = i; } } t1 = 0; for(long long i = l;i <= r;i++){ if(flag[i-l] == false&&t1 == 0){ t1 = 1; pre = i; } else if(flag[i-l] == false&&t1 == 1){ t1 = 2; t = i-pre; if(t == Max){ printf("%lld,%lld are most distant.\n", pre, i); break; } pre = i; } else if(flag[i-l] == false){ t = i-pre; if(t == Max){ printf("%lld,%lld are most distant.\n", pre, i); break; } pre = i; } } } } return 0; }