题目:从1-20个数字选择这些数字,并且把这些数字排成圈,使得相邻的两个数字的和为素数的排法有多少种?并一一枚举,跑了2分钟都没跑完,,,
# include<cstdio>
# include<iostream>
# include<cmath>
# include<cstdlib>
# include<cstring>
using namespace std;
int a[21];
int b[21];
int ans = 0;
int pd( int x,int y )
{
int k = 2;
int l = x+y;
while ( k<=sqrt(l)&&l%k!=0 )
k++;
if ( k>sqrt(l) )
return 1;
else
return 0;
}
int print()
{
ans++;
cout<<"<"<<ans<<">";
for ( int j = 1;j <= 20;j++ )
{
cout<<a[j]<<" ";
}
cout<<endl;
}
int search ( int t )
{
for ( int i = 1;i <= 20;i++ )
{
if (pd(a[t-1],i)&&(!b[i]))
{
a[t] = i;
b[i] = 1;
if ( t==20 )
{
if ( pd(a[20],a[1]))
print();
}
else
search(t+1);
b[i] = 0;
}
}
}
int main(void)
{
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
search(1);
cout<<ans<<endl;
system("pause");
return 0;
}