codeforces 237C.Primes on Interval

C. Primes on Interval
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

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 aa + 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 xx + 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.

这题做得我好蛋疼。本来用的方法是用一数组存1至t的素数个数至一个数组中p[t].然后求使p[x+l-1]-p[x]>=k的最大t。本来这个方法是对的,只要检验每个x是否满足即可。但我那时想,x可能要跑10^6,若再让l跑10^6不就会超时吗Orz..一我没注意看有2s,二我把二分用在了别的地方,不是判断l的大小上。所以我立即换了个方法。

因为我们要找k个素数,所以我就分别讨论原数组的素数总和小于k个,等于k个,大于k个的情形。可惜,我错在了忘记判断该数是否会超界。。

现在终于AC了。

#include<stdio.h>
#include<string.h>
int p[1000001],cun[1000009],tot;
void biao(int n)
{
	memset(p,0,sizeof(p));
	p[1]=1;p[0]=1;tot=0;
	for(int i=2;i<n;i++)
	{		
		if(!p[i])
		{
			cun[tot++]=i;
			for(int j=i+i;j<n;j+=i)
				p[j]=1;
		}
	}
}

int main()
{
	int T,i,k,j,a,b,xiao,da;
	biao(1000001);
	int front=0,rear=tot-1,mid;
	while(~scanf("%d%d%d",&a,&b,&k))
	{		
		{
			front=0;
			rear=tot-1;			
			int count,ans;
			while(front<rear)
			{
				mid=front+(rear-front)/2;
				if(cun[mid]>=a)rear=mid;
				else front=mid+1;
			}
			front=rear;
			count=0;
			while(cun[rear]<=b)
			{	
				count++;
				if(count<=k){rear++;if(rear==tot)break;}
				else break;;
			}
			if(count==k+1)
			{
				ans=cun[rear-1]-a+1;
				for(;;)
				{
					a=cun[front];
					if(ans<cun[rear]-a)ans=cun[rear]-a;	
					rear++;front++;
					if(cun[rear]-1>=b||rear==tot)break;	//我就是忘记判断rear==tot?		
									
				}
				if(ans<b-cun[front]+1)ans=b-cun[front]+1;
				printf("%d\n",ans);
			}
			else if(count==k)
				if(cun[rear-1]-a+1>b-cun[front]+1)
				printf("%d\n",cun[rear-1]-a+1);
				else printf("%d\n",b-cun[front]+1);
			else printf("-1\n");
		}
	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值