HOJ 1107 Prime Cuts

找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也爲素數。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章