Primes on Interval(二分 + 素数打表)

Primes on Interval
Time Limit:1000MS     Memory Limit:262144KB     64bit IO Format:%I64d & %I64u
Appoint description: 

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

A single 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

Input
2 4 2
Output
3
Input
6 13 1
Output
4
Input
1 4 3
Output
-1
题意:
求最小的l使 x, x + 1, ..., x + l - 1 there are at least k prime numbers;
简单二分;
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
const int MAXN = 1e6 + 100;
int dp[MAXN];
int vis[MAXN];
void db(){
    memset(vis, 0, sizeof(vis));
    vis[1] = 1;
    for(int i = 2; i <= sqrt(MAXN); i++){
        if(!vis[i]){
            for(int j = i * i; j < MAXN; j += i){
                vis[j] = 1;
            }
        }
    }
    dp[0] = 0;
    for(int i = 1; i < MAXN; i++){
        dp[i] = dp[i - 1];
        if(!vis[i])dp[i]++;
    }
}
bool js(int l, int a, int b, int k){
    for(int i = a; i <= b - l + 1; i++){
        if(dp[i + l - 1] - dp[i - 1] < k)return false;
    }
    return true;
}
int erfen(int l, int r, int a, int b, int k){
    int mid, ans = -1;
    while(l <= r){
        mid = (l + r) >> 1;
        if(js(mid, a, b, k)){
            ans = mid;
            r = mid - 1;
        }
        else l = mid + 1;
    }
    return ans;
}
int main(){
    db();
    int a, b, k;
    while(~scanf("%d%d%d", &a, &b, &k)){
        printf("%d
", erfen(0, b - a + 1, a, b, k));
    }
    return 0;
}
原文地址:https://www.cnblogs.com/handsomecui/p/5440258.html