using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace SeqListSort
{
/// <summary>
/// <ather>
/// lihonglin
/// </ather>
/// <content>
/// 把从1到20这20个数摆成一个环,要求相邻的两个数的和是一个素数。
///分析:用回溯算法,考察所有可能的排列
/// </content>
/// </summary>
class PrimeFor
{
static int n = 14;
static int[] a = new int[20];//a数组存放素数环
public static void InitPrimeFor()
{
for (int i = 0; i < 20; ++i )
{
a[i] = i + 1;
}
}
public static void Swap( int i, int j)
{
a[i] = a[i] + a[j] - (a[j] = a[i]);
}
static void PrintResult()
{
for (int i = 0; i < n; ++i)
{
Console.Write("{0,-4}" , a[i]);
}
Console.WriteLine();
}
static bool IsOK(int num)
{
for ( int i = 2; i <= (int)Math.Sqrt(num); ++i )
{
if (0 == num % i)
{
return false;
}
}
return true;
}
public static void Search(int k)
{
int i = 0;
if ( k > n - 1 )//判断结束条件
{
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);//继续探索
}
//回溯
Swap(k, i);
}
}
}
}
}