1022: Primes on Interval

Time Limit: 1 Sec  Memory Limit: 128 M

[​​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 aa + 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 ≤ 106a ≤ 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

6 13 1

1 4 3


Sample Output

3

4

-1


题意:给出三个正整数a,b,k,求最小的L(1<=L<=b-a+1),并且满足对于[a,b-L+1]种的任意一个数X,在[X,X+L-1]这L个数中,至少有k个素数。如果不存在满足条件的L,就输出-1


【分析】

题意非常简单,做法也很简单,只要先判断当L=b-a+1时有没有解,因为显然这个时候L是最大的,如果这个时候都没有解,那么当L更小的时候就更不可能有解。

在L=b-a+1时有解,那么也是很明显的用二分在[1,b-a=1]这个区间中找答案。

基本思路没有问题,如果超时那么就只能是判断素数的时候超时了。

这道题显然需要多次判断素数,而且基本上都是在重复判断。所以很显然,我们可以预处理一个素数表,就可以避免重复的判断素数。这里可以用筛法求素数。速度O(n loglog n);当然可以用线性筛法O(n);我这里用的是普通筛法。

用筛法预处理素数,这是第一个优化,但是显然我们每次都需要判断的是一个区间内的素数个数。

一个区间内的个数。显然可以用区间和表示,并且是最简单的区间和。这是第二个优化




【代码】

#include <stdio.h>
#include <math.h>
#include <string.h>
using namespace std;
const int maxn=1000005;
int sum[maxn]={0};
int prime[maxn]={0};
int a,b,k;
void find()
{
for(int i=2;i<maxn;i++)
{
sum[i]=sum[i-1];
if(prime[i]==0)
{
sum[i]++;
for(int j=1;i*j<=maxn;j++)
prime[i*j]=1;
}
}
}
int check(int x)
{
for(int i=a;i<=b-x+1;i++)
if(sum[i+x-1]-sum[i-1]<k)
return 0;
return 1;
}
int main()
{
find();
while(~scanf("%d%d%d",&a,&b,&k))
{
if(sum[b]-sum[a-1]<k)
{
printf("-1\n");
continue;
}
int left=1;
int right=b-a+1;
int num;
while(left<=right)
{
int mid=(left+right)/2;
if(check(mid))
{
num=mid;
right=mid-1;
}
else
left=mid+1;
}
printf("%d\n",num);

}
}