1022: Primes on Interval
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 145 Solved: 65
[ Submit][ Status][ Web Board]
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
Everay 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
Sample Output
#include <stdio.h>
#include <math.h>
#include <string.h>
using namespace std;
#define MAX 1000100
int sum[MAX]={0};
int su[MAX]={0};
int a,b,k;
void panduan()
{
int i,j;
for(i=2;i<MAX;i++)
{
sum[i]=sum[i-1];//表示前一个区间内有的素数给现在这个区间
if(su[i]==0)
{
sum[i]++;//如果i是素数则这个区间内的素数加1
for(j=1;i*j<=MAX;j++)//筛法求素数
su[i*j]=1;
}
}
}
int check(int L)
{
int i;
for(i=a;i<=b-L+1;i++)
{
if(sum[i+L-1]-sum[i-1]<k)
return 0;
}
return 1;
}
int main()
{
panduan();
int i,j,left,right,mid,L;
while(~scanf("%d%d%d",&a,&b,&k))
{
if(sum[b]-sum[a-1]<k)//判断a到b的范围内的素数如果小于k那接下来是不可能有它的子区间的素数是大于k的
{
printf("-1\n");//这里为什么要用a-1,我们把样例1带入,区间是2到4,如果我们算的是sum[b]-sum[a]那肯定不对
continue;//如果a是素数呢,那这样相当于你多减去一个素数了
}
left=1;
right=b-a+1;
while(left<=right)//二分法查找
{
mid=(left+right)/2;
if(check(mid))
{
L=mid;
right=mid-1;//继续寻找小的
}
else
{
left=mid+1;//往后找到L的几率比较大,如果中间位置不行了的话
}
}
printf("%d\n",L);
}
return 0;
}