找1到N之间的素数(包括1和N),如果素数数未偶数,则输出最中间的2*C个,否则输出最中间的2*C-1个
Input
Each input set will be on a line by itself and will consist of 2 numbers. The first number (1 <= N <= 1000) is the maximum number in the complete list of prime numbers between 1 and N. The second number (1 <= C <= N) defines the C*2 prime numbers to be printed from the center of the list if the length of the list is even; or the (C*2)-1 numbers to be printed from the center of the list if the length of the list is odd.
Output
For each input set, you should print the number N beginning in column 1 followed by a space, then by the number C, then by a colon (:), and then by the center numbers from the list of prime numbers as defined above. If the size of the center list exceeds the limits of the list of prime numbers between 1 and N, the list of prime numbers between 1 and N (inclusive) should be printed. Each number from the center of the list should be preceded by exactly one blank. Each line of output should be followed by a blank line. Hence, your output should follow the exact format shown in the sample output.
Sample Input
21 2 18 2 18 18 100 7
Sample Output
21 2: 5 7 11 18 2: 3 5 7 11 18 18: 1 2 3 5 7 11 13 17 100 7: 13 17 19 23 29 31 37 41 43 47 53 59 61 67
Solution:
#include <stdio.h>
#include <malloc.h>
//判断是否是素数,是返回1,不是返回0
int is_prime(int num)
{
if(num == 1 || num == 2 || num == 3)
return 1;
for(int i=2;i*i<=num;i++)
{
if(num%i == 0) return 0;
}
return 1;
}
//打印数组下标从i到j的数
void print(int *p,int i,int j)
{
for(;i<=j;i++)
{
printf(" %d",p[i]);
}
printf("\n\n");
}
int main()
{
int n,c;
int *p = NULL;
while(scanf("%d %d",&n,&c) == 2)
{
if(n>=1 && n<=1000 && c>=1 && c<=n)
{
p = (int *)malloc(sizeof(int)*(n/2+3));
p[0] = 0;
for(int i=1;i<=n;i++)
{
if(is_prime(i))
{
p[0]++;
p[p[0]] = i;
}
}
printf("%d %d:",n,c);
if(p[0]%2 == 0)
{
if(p[0] > c*2) //显示的个数小于总的素数数
print(p,p[0]/2-c+1,p[0]/2+c);
else
print(p,1,p[0]);
}
else
{
if(p[0] > c*2-1) //显示的个数小于总的素数数
print(p,p[0]/2+2-c,p[0]/2+c);
else
print(p,1,p[0]);
}
free(p);
p = NULL;
}
}
}
//注:此处指定1也为素数。