输入正整数n,把整数1,2,3,。。。,n 组成一个环,使得相邻连个整数之间和均为素数。
输出时从整数1开始逆时针排列。同一个环应恰好输出一次。n<=16。
样例输入:6
样例输出:1 4 3 2 5 6
1 6 5 2 3 4
解:
public class Main {
static int n;
static int[] a;
static int[] book;
static void fun(int cur) {
if (cur == n && su(a[0] + a[n - 1])) {
for (int i = 0; i < n; i++)
System.out.print(a[i] + " ");
System.out.println();
} else
for (int i = 2; i <= n; i++)
if (su(i + a[cur - 1]) && book[i - 1] == 0) {
a[cur] = i;
book[i - 1] = 1;
fun(cur + 1);
book[i - 1] = 0;
}
}
static boolean su(int num) {
if (num == 1)
return false;
for (int i = 2; i <= Math.sqrt(num); i++)
if (num % i == 0)
return false;
return true;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
n = in.nextInt();
a = new int[n];
book = new int[n];
a[0] = 1;
book[0] = 1;
fun(1);
}
}