HOJ 1107 Prime Cuts

本文介绍了一种算法,用于找出1到N之间的所有素数,并根据特定规则输出中间部分的素数。当素数总数为偶数时,输出中间2*C个素数;为奇数时,输出中间2*C-1个。该算法使用了素数判断函数和数组打印函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

找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也为素数。


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值