Prime Ring Problem
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.
Note: the number of first circle should always be 1.
![](https://i-blog.csdnimg.cn/blog_migrate/427b1dd2282412709d583cc17eda983e.gif)
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.
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
Source
题意:
相邻俩个数的加为素数,并且第一个数和最后一个数相加也要为素数。
代码:
#include<stdio.h>
#include<string.h>
#include<cmath>
int a[25];
int vis[25];
int b[25];
int n;
bool is_prime(int m)//判断素数
{
int i;
int gg=sqrt(m*1.0);
if(m==1)
return false;
for( i=2;i<=gg;i++)
if(m%i==0)
break;
if(i>gg)
return true;
return false;
}
void dfs(int x)
{
if(x==n)
{
if(is_prime(b[n-1]+1))
{
printf("%d",b[0]);
for(int i=1;i<n;i++)
printf(" %d",b[i]);
printf("\n");
}
return;
}
for(int i=2;i<=n;i++)
{
if(!vis[i]&&is_prime(a[i]+b[x-1]))
{
vis[i]=1;
b[x]=a[i];
dfs(x+1);
vis[i]=0;
}
}
}
int main()
{
int ans=0;
while(scanf("%d",&n)!=EOF&&n)
{
printf("Case %d:\n",++ans);
b[0]=1;
memset(vis,0,sizeof(vis));
for(int i=1;i<=n;i++)
a[i]=i;
dfs(1);
printf("\n");
}
return 0;
}