CodeForces 237C
二分查找的代码还是写不出来,只能套用模板,本题只要找到区间内的素数然后用二分把最小的l找出来
#include<iostream> #include<cstring> #include<algorithm> using namespace std; int a,b,c; const int maxn = 1000010; int sum[maxn],pri[maxn]; void init() { for(int i = 2;i < maxn;i++) { sum[i] = sum[i-1]; if(pri[i]) continue; sum[i]++; for(int j = i+i;j < maxn;j += i) pri[j] = 1; } } bool check(int mid) { for(int i = a;i <= b-mid+1;i++){ if(sum[i+mid-1]-sum[i-1] < c) return 0; } return 1; } int main() { cin >> a>> b>> c; init(); int x=0,y=0; if(sum[b]- sum[a-1] < c){ cout<< "-1" << endl; return 0; } int l = 1,r = b-a+1,ans; while(l <= r) { int mid = (l+r)>>1; if(check(mid)) ans = mid,r = mid-1; else l= mid+1; } cout<< ans<< endl; return 0; }