A ring is composed of n (even number) circles as shown in diagram. Put natural numbers 1, 2, … , 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
题意:一个环有n个数字组成,这个环中相邻的两个数字的和为素数
方法:由题意可知,n的取值范围为[0,16],所以判断的素数的范围为[3,31],可以在程序开始处先求解出这个范围中的素数都有哪些,之后使用深度优先算法,判断是否相邻的两个数字的和为素数
#include <cstdio>
#include <memory.h>
#include <algorithm>
using namespace std;
bool is_prime[40];
int is_used[20];
void prime(){
is_prime[2] = true;
for(int i=3; i<40; i++){
int j;
for(j=2; j<i;j++){
if(i%j == 0){
is_prime[i] = false;
break;
}
}
if(j == i)
is_prime[i] = true;
}
}
void dfs(int *A, int n, int cur){
if(cur == n && is_prime[A[0] + A[n-1]]){
for(int i = 0; i < n-1; i++)
printf("%d ", A[i]);
printf("%d\n", A[n-1]);
}
else{
for(int i = 2; i <= n; i++){
if(!is_used[i] && is_prime[i + A[cur-1]]){
A[cur] = i;
is_used[i] = 1;
dfs(A, n, cur+1);
is_used[i] = 0;
}
}
}
}
int main()
{
int n;
int cnt = 0;
prime();
while(~scanf("%d", &n)){
if(cnt != 0)
printf("\n");
printf("Case %d:\n", ++cnt);
int A[20];
A[0] = 1;
memset(is_used, 0, sizeof(int));
dfs(A, n, 1);
}
return 0;
}