素数环问题

0

#include<iostream>
#include<cmath>
using namespace std;
static int count=0;
bool Prime(int m)                                     //判断是否是素数
{
int p=(int)sqrt((double)m);
for(int i=2;i<=p;i++)
if(m%i==0)
return false;
return true;
}
inline void Swap(int a,int b)                          //两数交换
{
int temp;
temp=a;a=b;b=temp;
}
void Perm(int *ary,int k,int m)                       //递归求所有排序
{
if(k==m)                                        //递归边界条件
{
bool temp=true;
for(int i=0;i<m;i++)
if(!Prime(ary[i]+ary[i+1]))
{ temp=false;break;}
if(Prime(ary[0]+ary[m])&&temp)
for(int j=0;j<m;j++)
cout<<ary[j]<<' ';
cout<<ary[m]<<endl;
}
else
{
for(int optr=k;optr<=m;optr++)
{
Swap(ary[k],ary[optr]);
Perm(ary,k+1,m);
Swap(ary[k],ary[optr]);
}
}
return ;
}
int main()
{
int ary[21];
int num;
while(cin>>num)
{
if(num<1||num>19)
break;
count++;
cout<<"Case "<<count<<":"<<endl;
for(int i=0;i<num;i++)
ary[i]=i+1;
Perm(ary,0,num-1);

}
return 0;
}

Jeick | 初学一级 | 园豆：195

0

0

dfs，

#include <stdio.h>
#include <string.h>
bool prime[45]={0,0,1,1,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0,0,0,0,1,0,1,0,0};
int n;
int visted[22],num[22];
void dfs(int count){
if(count==n+1&&prime[num[n]+num[1]]){
for(int i=1;i<=n;++i)
printf("%d ",num[i]);
printf("\n");
}
else for(int i=2;i<=n;++i)
if(!visted[i]&&prime[i+num[count-1]]){
visted[i]=1; num[count]=i;
dfs(count+1);visted[i]=0;
}
}
int main(){
int k=0;
while(scanf("%d",&n),n){
printf("Case %d:\n",++k);
if(n==1)printf("1\n");