usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceseqlistsort{/// <summary> /// <ather> ///Lihonglin/// </ather> /// <content> ///The 20 numbers from 1 to 20 are placed in a ring, requiring the number of adjacent two and a prime. ///Analysis: Using backtracking algorithms to investigate all possible permutations/// </content> /// </summary> classPrimefor {Static intn = -; Static int[] A =New int[ -];//A array holds prime rings Public Static voidinitprimefor () { for(inti =0; I < -; ++i) {A[i]= i +1; } } Public Static voidSwap (intIintj) {A[i]= A[i] + a[j]-(a[j] =A[i]); } Static voidPrintresult () { for(inti =0; I < n; ++i) {Console.Write ("{0,-4}", A[i]); } Console.WriteLine (); } Static BOOLIsOK (intnum) { for(inti =2; I <= (int) math.sqrt (num); ++i) {if(0= = num%i) {return false; } } return true; } Public Static voidSearch (intk) {inti =0; if(k > N-1)//Judgment End Condition { if(IsOK (a[0] + a[n-1])) Printresult (); return; } Else { for(i = k; i < n; + +)i) {Swap (k, i); if(IsOK (A[k-1] +A[k])) {Search (k+1);//continue to explore } //BacktrackingSwap (k, i); } } } }}
The prime circle of backtracking algorithm