uva 524 - Prime Ring Problem

本文介绍了一种生成特定环形结构中满足相邻两数之和为质数的自然数序列的方法。通过递归搜索算法实现,同时提出了两种优化策略:预计算质数并存储在数组中以及利用数字奇偶性减少搜索范围。

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

A ring is composed of n (even number) circles as shown in diagram. Put natural numbers$1, 2, \dots, n$ into each circle separately, and the sum of numbers in two adjacent circles should be a prime.

Note: the number of first circle should always be 1.

Input:

n (0 <n <= 16)


Output:

The output format is shown as sample below. Each row represents a series of circle numbers in the ring beginning from 1 clockwisely and anticlockwisely. The order of numbers must satisfy the above requirements.


You are to write a program that completes above process.

Sample input:

6
8

Sample output:

Case 1:
1 4 3 2 5 6
1 6 5 2 3 4

Case 2:
1 2 3 8 5 6 7 4
1 2 5 8 3 4 7 6
1 4 7 6 5 8 3 2
1 6 7 4 3 8 5 2

#include <math.h>
#include <stdio.h>

int N;
int result[50];
int visit[50];

int is_prime(int n)
{
	int max = sqrt(n);
	int i = 2;
	while(i <= max)
	{
		if(n % i == 0)
		{
			return 0;
		}
		i++;
	}

	return 1;
	
}

void print_result(void)
{
	int i = 1;
	while(i <= N)
	{
		printf("%d ", result[i]);
		i++;
	}
	printf("\n");
}
void search(int current_count)
{
	if(current_count == N && is_prime(1 + result[current_count]))
	{
		print_result();
		visit[result[current_count]] = 0;
		return;
	}
	int i;
	for(i = 2; i <= N; i++)
	{
		if(visit[i] == 0  && is_prime(i + result[current_count]) )
		{
				visit[i] = 1;
				result[current_count + 1] = i;
				search(current_count + 1);
		}	
	}

	visit[result[current_count]] = 0;	
}


int main(int argc, char **argv)
{
	int i = 1;
	while(scanf("%d", &N) != EOF)
	{
		
		result[1] = 1;
		visit[1] = 1;
		printf("Case %d:\n", i);
		i++;
		search(1);
	}
	return 0;
}

这个代码可以从下面两点优化:

1. 预先把数字是否为质数保存到数组里面,而不是一个个的去计算。

2. 考虑到数字的奇偶行,下面一行可:

for(i = 2; i <= N; i++)
可以改为:

 for(i = (current_count+1) %2 + 2; i <= N; i+=2)


References:

1. http://www.programering.com/a/MTMwIDNwATU.html

2. http://www.tuicool.com/articles/Ezuum2a

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值