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.
A single line contains three space-separated integers a, b, k (1 ≤ a, b, k ≤ 106; a ≤ b).
In a single line print a single integer — the required minimum l. If there‘s no solution, print -1.
2 4 2
3
6 13 1
4
1 4 3
-1
/* 2016年4月21日23:49:25 题意:给出三个正整数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最大,若此时都无解,则肯定无解。 若有解,则1 ≤ L≤ b - a + 1,二分求最小的L即可。 */
1 # include <iostream> 2 # include <cstdio> 3 # include <cstring> 4 # include <algorithm> 5 # include <queue> 6 # include <vector> 7 # include <cmath> 8 # define INF 0x3f3f3f3f 9 using namespace std; 10 const int N = 1e6 + 5; 11 int vis[N], cnt[N]; 12 13 // 标记素数 14 void Sign() 15 { 16 int i, j; 17 int m = (int)sqrt(N); // 可能是标记时 这个数不需要太大 后面的数可能在前面判断时都被标记过了 18 memset(vis, 0, sizeof(vis)); // 如果不开根号 好像会有问题... 19 for (i = 2; i <= m; i++){ 20 if (vis[i]) continue; 21 for (j = i; j*i <= N; j++){ 22 if (!vis[j*i]) 23 vis[j*i] = 1; 24 } 25 } 26 } 27 // cnt[i] 表示 从1到 i一共有多少个素数 28 void Count() 29 { 30 Sign(); 31 cnt[0] = cnt[1] = 0; 32 for (int i = 2; i <= N; i++){ 33 if (!vis[i]) cnt[i] = cnt[i-1] + 1; 34 else cnt[i] = cnt[i-1]; 35 } 36 } 37 // 判断当前的l是否满足题目要求 38 int Check(int a, int b, int k, int l) 39 { 40 int r = b - l + 1; 41 for (int i = a; i <= r; i++){ 42 if (cnt[i + l - 1] - cnt[i - 1] >= k) 43 continue; 44 return 0; 45 } 46 return 1; 47 } 48 // 二分求 l的最小值 49 int Solve(int a, int b, int k) 50 { 51 int L = 1, R = b-a+1; 52 while (L <= R){ 53 int mid = (L + R) / 2; 54 if (Check(a, b, k, mid)) 55 R = mid - 1; 56 else L = mid + 1; 57 } 58 return L; 59 } 60 61 int main(void) 62 { 63 int a, b, k, ans; 64 Count(); 65 while (~scanf("%d %d %d", &a, &b, &k)){ 66 if (!Check(a, b, k, b - a + 1)) //此处判断 l的最大值是否符合 67 printf("-1\n"); 68 else { 69 ans = Solve(a, b, k); 70 printf("%d\n", ans); 71 } 72 } 73 74 return 0; 75 }
原文:http://www.cnblogs.com/hyq123456/p/5419497.html