例5.1 素数环(因书中20个数等待时间长,所以更改为10,也可以把10改成任何数,代表素数环中数的个数)
#include<bits/stdc++.h>
using namespace std;
bool b[11]={0};
int total=0,a[11]={0};
int search(int);//回溯过程
int print();//输出方案
bool pd(int,int);//判断素数
int main()
{
search(1);
cout<<total<<endl;//输出总方案数
return 0;
}
int search(int t)
{
for(int i=1;i<=10;i++)//有二十个数可选
{
if(pd(a[t-1],i) && (!b[i]))//判断与前一个数是否构成素数及该数是否可用
{
a[t]=i;
b[i]=1;
if(t==10)
{
if(pd(a[10],a[1]))
print();
}
else
search(t+1);
b[i]=0;
}
}
}
int print()
{
total++;
cout<<"<"<<total<<">";
for(int j=1;j<=10;j++)
cout<<a[j]<<" ";
cout<<endl;
}
bool pd(int x,int y)
{
int k=2,i=x+y;
while(k<=sqrt(i) && i%k!=0)
k++;
if(k>sqrt(i))
return 1;
else
return 0;
}
例5.2
#include<bits/stdc++.h>
using namespace std;
int num=0,a[10001]=