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.
Input
n (0 < n < 20).
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. Print solutions in lexicographical order.
You are to write a program that completes above process.
Print a blank line after each case.
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<iostream>
#include<cstring>
using namespace std;
int a[10005],vis[10005];
int n;
bool isprime(int x){//判断是不是素数
if(x==1||x==0)
return 0;
for(int i=2;i<=x/2;i++){
if(x%i==0)
return 0;
}
return 1;
}
void dfs(int step){
if(step==n+1){//满足条件
for(int i=1;i<=n;i++){
if(i!=1)
cout<<" ";
cout<<a[i];
}
cout<<endl;
return ; //跳出
}
for(int i=1;i<=n;i++){//从1到n开始试
if(vis[i]==1)//用过了
continue;
if(isprime(a[step-1]+i)){//两个数的和,是素数
if(step==n){
if(!isprime(i+1))//最后一个圈里的,他的下一个是1
continue;
}
a[step]=i;//存进去
vis[i]=1;//标记
dfs(step+1);//下一步
vis[i]=0;//取消标记
}
}
}
int main(){
int count=1;
while(~scanf("%d",&n)){
memset(a,0,sizeof(a));
memset(vis,0,sizeof(vis));//初始化
a[1]=1;//第一个必须是1
vis[1]=1;//标记
cout<<"Case "<<count++<<":"<<endl;
dfs(2);//从2 开始
cout<<endl;
}
}