Ka的递归编程练习 Part7|回溯前传一|素数环!

 1 #include <stdio.h>
 2 #include <math.h>
 3 #define MAX 12 
 4 int used[21]={0},resl[21]={0},zs[50]={0};//used=已使用 resl=结果 zs=质数 
 5 int total=0;
 6 void output()
 7 {
 8     total++;
 9     printf("<%d>:",total);
10     int i;
11     for(i=1;i<=MAX;i++)
12         printf("%d ",resl[i]);
13     printf("
");
14 }
15 int search(int n) //第n层 
16 {
17     int i;
18     for(i=1;i<=MAX;i++) //20个数可选
19         if(used[i]==0&&zs[resl[n-1]+i]==1) //若这个数可选 
20         {
21             resl[n]=i; //做一做标记 
22             used[i]=1;
23             if(n==MAX)  //如果已经来到第MAX层 
24                 {if(zs[resl[MAX]+resl[1]]==1) output();}    //这里if比较多,不像py用缩进判断语句块,还是圈起来好。 
25             else search(n+1);
26             used[i]=0; //恢复给下一次准备 
27         } 
28 }
29 int judge(int n)
30 {
31     int i;
32     double m=sqrt(n);
33     for(i=2;i<=m;i++)
34         if(n%i==0) return -1;
35     return 1;
36 }
37 void dabiao()
38 {
39     int i;
40     for(i=1;i<=40;i++)
41     {
42         zs[i]=judge(i);
43         //printf("%d
",zs[i]);
44     }
45         
46 }
47 int main()
48 {
49     dabiao();
50     search(1);
51     return 0;
52 }
原文地址:https://www.cnblogs.com/KakagouLT/p/4508233.html