The prime number ring is a computer program problem. It refers to the n integers from 1 to n forming a ring. If any two adjacent numbers are added, the result is a prime number, then the ring becomes a prime number ring .
Now it is required to enter an n, find the number of prime number rings in a circle of n numbers, and specify that the first number is 1.
#include<iostream>
#include<math.h>
using namespace std;
int n=0;
int a[100]; //对应环
int visit[100]; //标记数组 0表示未用 1表示已用
int check(int k) //判断数字x是否为整数
{
int i,n;
n=(int)sqrt(k);
for(i=2;i<=n;i++)
if(k%i==0) return 0;
return 1;
}
void dfs(int step)
{
if(step==n&&check(a[0]+a[n-1])==1) //全部填满而且第一个元素和最后一个元素满足就输出
{
for(int i=0;i<n;i++)
cout<<a[i]<<' ';
cout<<endl;
return ;
}
else
{
for(int i=2;i<=n;i++)
{
if(visit[i]==0&&check(i+a[step-1])==1){ //i没有被占用且与前一个元素符合
a[step]=i;
visit[i]=1;
dfs(step+1);
visit[i]=0;
}
}
}
}
int main(void)
{
cin>>n;
a[0]=1; //因为是环所以第一个元素固定
visit[1]=1; //1已用
dfs(1); //从第一个元素开始
return 0;
}
This kind of backtracking problem is similar to the Eight Queens Hamiltonian circuit problem.