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.
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 <cstdio>
#include <iostream>
#include <cmath>
using namespace std;
//判断素数
int isprime(int n)
{
int i;
if(n==1) return false;
for(i=2;i<=sqrt(n);i++)
if(n%i==0)
return false;
return true;
}
//判断当前序列是否满足条件
int isok(int a[],int last,int curvalue)//curvalue是当前值,a[last]是前一个值
{
if(last<0) return true;//第一个元素没有前驱元素 返回真
if(!((curvalue+a[last])&1))//相邻元素和为偶数,偶数肯定不是素数!
return false;
if(!(isprime(curvalue+a[last])))//相邻元素和不为素数
return false;
for(int i=0;i<=last;i++)
if(a[i]==curvalue)//去重curvalue没有出现过
return false;
return true;
}
//输出
void print(int a[],int n)
{
for(int i=0;i<n-1;i++)
printf("%d ",a[i]);
printf("%d\n",a[n-1]);
}
void primecircle(int a[],int n,int t)
{
if(n&1)//输入N为奇数,肯定不满足,因为肯定会有两个奇数排在一起~
return ;
if(t==n)
{
if(isprime(a[0]+a[n-1]))
print(a,n);
}
else{
for(int i=2;i<=n;i++)
{
a[t]=i;
if(isok(a,t-1,i))//如果当前元素满足条件
primecircle(a,n,t+1);
}
}
}
int main()
{
int a[30],n,k=1,i,j;
while(scanf("%d",&n)!=EOF){
printf("Case %d:\n",k++);
a[0]=1;
isprime(a[0]);
for(i=1,j=2;i<n;i++,j++){
a[i]=j;
isprime(a[i]);
}
primecircle(a,n,1);
printf("\n");
}
return 0;
}
有一篇关于素数环博客写的特别好,有兴趣的可以参考#本人的收藏#~~嘻嘻 希望对你有帮助~