题源 codeforces237C
E - E
Time Limit:1000MS Memory Limit:262144KB 64bit IO Format:%I64d & %I64u
Submit
Status
Practice
CodeForces 237C
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.
Sample Input
Input
2 4 2
Output
3
Input
6 13 1
Output
4
Input
1 4 3
Output
-1
之前的思路大致是对的,但有一些混乱,所以有些是错的
正确的思路
本题时间限制挺严,正常思维是利用三重循环暴力求解,但是会TLE,而且二重循环也会TLE。还有一个问题是,判断素数不能利用函数判断,这样肯定会超时,所以就利用打表标记的办法,把是素数的标记为1,不是的标记为0,
下面在去掉一重循环的方法是求区间内素数的个数,就是将a—b区间上的素数存到p【】数组中~~~,如果p【b】<k那么输出-1.
下面定义ans=1,ans从1开始增加判断是否符合条件。最后输出ans。
代码如下:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int p[1005000]= {0};
int s[1005000]= {0};
int sum[1005000]= {0};
int a,b,k,st,ans;
void mkprime() //打素数表
{
for(int i=2; i<=b; ++i) p[i]=1;
for(int i=2; i<=1000; ++i)
if(p[i])
{
for(int j=i*i; j<=b; j+=i) p[j]=0;
}
}
int main()
{
cin >> a >> b >> k;
mkprime();
for(int i=a+1; i<=b; ++i) p[i]+=p[i-1];
p[a-1]=0;
if(p[b]<k)
cout <<-1 << endl;
else //判断是否符合条件;
{
int l=1,st;
for(st=a-1; st+ans<b; ++st)//ans代表l;st代表x
while(st+ans<b&&p[st+ans]-p[st]<k)//st+ans代表x,x+1,。。。。,p[st+ans]-p[st]代表st+ans到st之间素数的个 ++ans;
for(st=b; p[b]-p[st]<k; --st);//判断多个,找出最小的
if(b-st>ans) ans=b-st;
cout << ans << endl;
}
return 0;
}