Primes on Interval(CF-237C)

本文介绍了一种算法,用于解决在给定区间内寻找最短子区间的问题,该子区间包含至少k个质数。通过使用素数筛和二分搜索,文章详细阐述了如何高效地找到满足条件的最小长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Problem 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 ≤ 106; a ≤ b).

Output

In a single line print a single integer — the required minimum l. If there's no solution, print -1.

Examples

Input

2 4 2

Output

3

Input

6 13 1

Output
4

Input

1 4 3

Output
-1

题意:给出 a、b、k 三个数,要求在区间 [a,b] 中找一个长度 l,使得对区间中任意一个位置到这个位置加上 l 后的子区间中存在 k 个质数,求最小的长度 l

思路:

首先用素数筛打一个素数表

由于 a、b 的数据范围可达 1E6,单纯的暴力一定会 TLE,而题目的关键是要求一个最小的长度,那么可以使用二分去枚举长度,找一个最小的解

需要注意的是,如果单纯使用素数表进行统计的话,依然会 TLE,需要考虑对素数表做出优化,求一个素数表的前缀和,用于计算第 i 个数前有多少个素数

Source Program

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<string>
#include<cstring>
#include<cmath>
#include<ctime>
#include<algorithm>
#include<utility>
#include<stack>
#include<queue>
#include<vector>
#include<set>
#include<map>
#include<bitset>
#define EPS 1e-9
#define PI acos(-1.0)
#define INF 0x3f3f3f3f
#define LL long long
const int MOD = 1E9+7;
const int N = 1000000+5;
const int dx[] = {-1,1,0,0,-1,-1,1,1};
const int dy[] = {0,0,-1,1,-1,1,-1,1};
using namespace std;

int prime[N],cnt;
bool bprime[N];
int sum[N];
void make_prime() {
    memset(bprime,false,sizeof(bprime));
    bprime[0]=true;
    bprime[1]=true;
    for(int i=2;i<N;i++){
        if(!bprime[i]){
            prime[cnt++]=i;
            for(int j=i*2;j<N;j+=i){
                bprime[j]=true;
            }
        }
    }
}

bool judge(int a,int b,int k,int x) {
    for(int i=a;i<=b-x+1;i++)
        if(sum[i+x-1]-sum[i-1]<k)
            return false;
    return true;
}
int main() {
    make_prime();
    for(int i=1;i<=N;i++) {
        sum[i]=sum[i-1];
        if(!bprime[i])
            sum[i]++;
    }

    int a,b,k;
    scanf("%d%d%d",&a,&b,&k);
    int res=INF;
    int left=1,right=b-a+1;
    while(left<right){
        int mid=(left+right)/2;
        if(judge(a,b,k,mid))
            right=mid;
        else
            left=mid+1;
    }

    if(judge(a,b,k,left))
        printf("%d\n",left);
    else
        printf("-1\n");
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值