Problem Description
You've decided to carry out a survey in the theory of prime numbers. Let us remind you that a prime number is a positive integer that has exactly two distinct positive integer divisors.
Consider positive integers a, a + 1, ..., b (a ≤ b). You want to find the minimum integer l (1 ≤ l ≤ b - a + 1) such that for any integer x (a ≤ x ≤ b - l + 1) among l integers x, x + 1, ..., x + l - 1 there are at least k prime numbers.
Find and print the required minimum l. If no value l meets the described limitations, print -1.
Input
A single line contains three space-separated integers a, b, k (1 ≤ a, b, k ≤ 106; a ≤ b).
Output
In a single line print a single integer — the required minimum l. If there's no solution, print -1.
Examples
Input
2 4 2
Output
3
Input
6 13 1
Output
4Input
1 4 3
Output
-1
题意:给出 a、b、k 三个数,要求在区间 [a,b] 中找一个长度 l,使得对区间中任意一个位置到这个位置加上 l 后的子区间中存在 k 个质数,求最小的长度 l
思路:
首先用素数筛打一个素数表
由于 a、b 的数据范围可达 1E6,单纯的暴力一定会 TLE,而题目的关键是要求一个最小的长度,那么可以使用二分去枚举长度,找一个最小的解
需要注意的是,如果单纯使用素数表进行统计的话,依然会 TLE,需要考虑对素数表做出优化,求一个素数表的前缀和,用于计算第 i 个数前有多少个素数
Source Program
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<bitset>
#define EPS 1e-9
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LL long long
const int MOD = 1E9+7;
const int N = 1000000+5;
const int dx[] = {-1,1,0,0,-1,-1,1,1};
const int dy[] = {0,0,-1,1,-1,1,-1,1};
using namespace std;
int prime[N],cnt;
bool bprime[N];
int sum[N];
void make_prime() {
memset(bprime,false,sizeof(bprime));
bprime[0]=true;
bprime[1]=true;
for(int i=2;i<N;i++){
if(!bprime[i]){
prime[cnt++]=i;
for(int j=i*2;j<N;j+=i){
bprime[j]=true;
}
}
}
}
bool judge(int a,int b,int k,int x) {
for(int i=a;i<=b-x+1;i++)
if(sum[i+x-1]-sum[i-1]<k)
return false;
return true;
}
int main() {
make_prime();
for(int i=1;i<=N;i++) {
sum[i]=sum[i-1];
if(!bprime[i])
sum[i]++;
}
int a,b,k;
scanf("%d%d%d",&a,&b,&k);
int res=INF;
int left=1,right=b-a+1;
while(left<right){
int mid=(left+right)/2;
if(judge(a,b,k,mid))
right=mid;
else
left=mid+1;
}
if(judge(a,b,k,left))
printf("%d\n",left);
else
printf("-1\n");
return 0;
}