Primes on Interval

题意:找到最小的一个在[1, b - a+ 1]上的数l , 使得属于[a, b - l + 1]上的所有x满足[x, x + l - 1]都至少有k个素数。 


分析:l越小, x变多, 同时x +l - 1上的素数也越少。所以可以二分l找到最小值。  预处理素数。


#include <iostream>
#include <cstdio>
#include <queue>
#include <algorithm>
#define MAX 1005
#include <complex>
#include <ctime>
#include <cstdlib>
#include <cstring>
#include <string>
#define INF 1e8
#define MAX (int)1e6+ 5
using namespace std;
bool notPrime[MAX];
void makePrime(){
    notPrime[0] = notPrime[1] = true;
    for(int i = 2; i < sqrt(MAX); i++){
        if(!notPrime[i])
        for(int j = i * 2; j < MAX; j+= i){
            notPrime[j] = true;
        }
    }
//    for(int i = 0; i < 100; i++){
//        if(!notPrime[i])cout<<i<<endl;
//    }
}
int a, b, k;
bool check( int key){
    int ans = 0;
    for(int i = a; i <= a + key - 1; i++){
       if(!notPrime[i])ans++;
    }
    if(ans < k)return false;
    for(int i = a + key; i <= b; i++){
        if(!notPrime[i])ans ++;
        if(!notPrime[i - key])ans--;
        if(ans < k)return false;
    }
    return true;
}
void b_search(){
    int l = 0, r = b  -  a + 2;
    while(l + 1 < r){
        int mid = (l + r)>>1;
        if(check(mid)){
            r = mid;
        }else {
            l  = mid;
        }
    }
    if(r > 0 && r < b - a + 2)cout<<r<<endl;
    else puts("-1");
}
int main()
{
    makePrime();
    while(cin>>a>>b>>k){
        b_search();
    }
    return 0;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值