题目链接:https://cn.vjudge.net/contest/319720#problem/B
题意:给出两个数 n、c,求从 1~N 的素数序列,若素数个数为奇数,则输出序列中心的 2*c-1 个素数,若为偶数,则输出序列中心的 2*c 个素数。若 c 大于素数个数,则输出整个序列。
思路:
打表求素数,再计算序列中心位置,然后判断奇偶输出即可。注意这里的序列中心的意思( = = 一开始理解错了)
然后这题让我掌握一下如何输出序列中心的方法吧。
1 #include<iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<cmath> 5 #include<algorithm> 6 #include<string> 7 #include<cstdlib> 8 #include<queue> 9 #include<set> 10 #include<map> 11 #include<stack> 12 #include<ctime> 13 #include<vector> 14 #define INF 0x3f3f3f3f 15 #define PI acos(-1.0) 16 #define N 1100 17 #define MOD 1e9+7 18 #define E 1e-6 19 #define LL long long 20 using namespace std; 21 int prime[N],cnt=1; 22 bool bprime[N]; 23 void make_prime() 24 { 25 memset(bprime,true,sizeof(bprime)); 26 bprime[0]=false; 27 28 for(int i=2;i<=N;i++) 29 for(int j=i+i;j<=N;j+=i) 30 bprime[j]=false; 31 32 for(int i=0;i<=N;i++) 33 if(bprime[i]) 34 prime[cnt++]=i; 35 } 36 int main() 37 { 38 make_prime(); 39 40 int n,c; 41 while(scanf("%d%d",&n,&c)!=EOF&&(n+c)) 42 { 43 int pos=0; 44 for(int i=1;i<cnt;i++)//求序列中心 45 { 46 if(prime[i]<=n&&prime[i+1]>n) 47 { 48 pos=i; 49 break; 50 } 51 } 52 53 printf("%d %d: ",n,c); 54 55 if (c>pos){ 56 for (int i=1;i<=pos;i++){ 57 printf("%d ",prime[i]); 58 } 59 printf(" "); 60 continue; 61 } 62 63 64 if(pos%2) 65 { 66 for(int i=(pos-(c*2-1))/2+1;i<=(pos-(c*2-1))/2+c*2-1;i++) 67 printf("%d ",prime[i]); 68 printf(" "); 69 } 70 else 71 { 72 for(int i=(pos-c*2)/2+1;i<=(pos-c*2)/2+c*2;i++) 73 printf("%d ",prime[i]); 74 printf(" "); 75 } 76 } 77 78 return 0; 79 }