题意:输入两个数n和c你需要输出1~n中,所有素数中间2*c-1个素数如果其中有奇数个素数,如果是偶数个输出2*c个。
思路:打素数表,然后通过二分法找到两头素数,之后再取中间。
代码如下:
#include<cstdio>
#include<algorithm>
#include<iostream>
#include<cstring>
using namespace std;
typedef long long LL;
#define INF 0x3f3f3f3f
int prime[500005];
bool bo[1000005];
int prime_table()
{
int flag=1,i,j;
memset(bo,0,sizeof(bo));
bo[0]=bo[1]=1;
for(i=2;i<=1000;i++)
{
if(!bo[i])
{
j=i*i;
for(;j<=1000000;j+=i)
{
bo[j]=1;
}
}
}
for(i=0;i<=10000;i++)
{
if(!bo[i])
prime[flag++]=i;
}
return flag;
}
int ans;
int Search(int x)
{
int left=0,right=ans,mid;
while(left<=right)
{
mid=(left+right)>>1;
if(prime[mid]==x)
{
return mid+1;
}
if(prime[mid]<x&&prime[mid+1]>x)
{
return mid+1;
}
if(prime[mid]>x&&prime[mid-1]<x)
{
return mid;
}
if(prime[mid]<x)
{
left=mid+1;
}
if(prime[mid]>x)
{
right=mid-1;
}
}
}
int main()
{
int n,c;
ans=prime_table();prime[0]=1;
while(~scanf("%d%d",&n,&c)){
int sum=Search(n);
//printf("%d\n",sum);
printf("%d %d: ",n,c);
if(sum%2==0)
{
int cnt=(sum-2*c)/2;int t=2*c;
if(t>sum)
{
for(int i=0;i<sum-1;i++)
{
printf("%d ",prime[i]);
}
printf("%d\n\n",prime[sum-1]);
}
else{
while(t>1)
{
t--;
printf("%d ",prime[cnt]);
cnt++;
}
printf("%d\n\n",prime[cnt]);
}
}
else
{
int cnt=(sum-(2*c-1))/2;int t=2*c-1;
if(t>sum)
{
for(int i=0;i<sum-1;i++)
{
printf("%d ",prime[i]);
}
printf("%d\n\n",prime[sum-1]);
}
else{
while(t>1)
{
t--;
printf("%d ",prime[cnt]);
cnt++;
}
printf("%d\n\n",prime[cnt]);
}
}
}
}