翻译:n个数字(1,2,3...n)围成一个圈,要求相邻的两个数字之和是质数。题目要求根据给出的n,计算所有能够组成满足条件的圈的数字序列。

解题思路:

首先选择1,然后选择和1相加等于质数的数字,可能有很多种情况,例如(n=6的情况):

1+21+41+6然后针对每种情况,再选择与第二个数的和为质数的数字,得到下面的序列

1+2+31+2+51+4+31+6+5直到所有的数字都选择完,把所有的组合列出即可。

 

描述


A ring is compose of n circles as shown in diagram. Put natural number 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.



输入


n (0 < n < 20).


输出


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. Print solutions in lexicographical order.
You are to write a program that completes above process.
Print a blank line after each case.


样例输入


6
8



样例输出


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<iostream>
#include<cstring>
#include<cmath>
using namespace std;
int a[50],f[50],ans=0,m,flag;
int sd[41];
int fun(int c)
{ int i;
for( i=2;i<=sqrt(c);i++)
if(c%i==0)return 0;
if(i>sqrt(c))return 1;
}
void dfs(int c)
{

a[1]=1;
if(c>m&&sd[f[1]+f[m]])
{
if(!flag)
{
cout<<"Case "<<ans<<":"<<endl;
flag=1;
}
for(int i=1;i<m;i++)
{
cout<<f[i]<<" ";
}
cout<<f[m]<<endl;
}
else
{
for(int i=2;i<=m;i++)
{
f[c]=i;
if(!a[i]&&sd[(f[c-1]+f[c])])
{
a[i]=1;
// if(m%2==0)
dfs(c+1);
a[i]=0;
}
}
}
}
int main()
{
int n,a[100];
while(cin>>m)
{
ans++;
flag=0;
memset(sd,0,sizeof(sd));
for(int i=1;i<=40;i++)
if(fun(i))sd[i]=1;
memset(a,0,sizeof(a));
f[1]=1;
if(m%2==0)
dfs(2);
else
cout<<"Case "<<ans<<":"<<endl;
cout<<endl;
}
return 0;
}