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 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
Sample Input
Sample Output
题意:给出三个正整数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);我这里用的是普通筛法。
用筛法预处理素数,这是第一个优化,但是显然我们每次都需要判断的是一个区间内的素数个数。
一个区间内的个数。显然可以用区间和表示,并且是最简单的区间和。这是第二个优化
【代码】