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 integerx (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.
Sample Input
2 4 2
3
6 13 1
4
1 4 3
-1
题意 找到最小的l满足1 <= l <= b - a + 1,使得对于任意的x(a <= x <= b - l + 1)均有[x, x + l - 1]里面至少有k个质数
素数打表 标记前i个数中有多少个素数 先判断最大的l不符合直接输出-1 否则用二分查找最小的l
#include<cstdio>
#include<algorithm>
using namespace std;
int su[1000010];
int vis[1000010];//标记有多少素数
void dabiao()//素数打表
{
for(int i=2;i<=1000010;i++)
{
if(su[i]==1)
{
continue;
}
for(int j=2*i;j<=1000010;j+=i)
{
su[j]=1;
}
}
su[0]=1;
su[1]=1;
}
void sushu()//标记前i个数有多少个素数
{
dabiao();
vis[0]=0;
for(int i=1;i<1000010;i++)
{
if(!su[i])
{
vis[i]=vis[i-1]+1;
}
else
{
vis[i]=vis[i-1];
}
}
}
bool panduan(int a,int b,int k,int l)
{
int s=b-l+1;
for(int i=a;i<=s;i++)
{
if(vis[i+l-1]-vis[i-1]>=k)
{
continue;
}
else
{
return 0;
}
}
return 1;
}
int erfen(int a,int b,int k)
{
int mid, l=1,r=b-a+1;
while(l<=r)
{
mid=(l+r)/2;
if(panduan(a,b,k,mid))
{
r=mid-1;
}
else
{
l=mid+1;
}
}
return l;
}
int main()
{
sushu();
int a,b,k;
while(scanf("%d%d%d",&a,&b,&k)!=EOF)
{
if(!panduan(a,b,k,b-a+1))
{
printf("-1
");
}
else
{
printf("%d
",erfen(a,b,k));
}
}
return 0;
}