素数环 蓝桥杯DFS java
素数环
难度:2
描述
有一个整数n,把从1到n的数字无重复的排列成环,且使每相邻两个数(包括首尾)的和都为素数,称为素数环。
为了简便起见,我们规定每个素数环都从1开始。例如,下图就是6的一个素数环。
输入n<16
样例输入
6
8
3
样例输出
Case 1:
1 4 3 2 5 6
1 6 5 2 3 4
Case 2:
1 2 3 8 5 6 7 4
1 2 5 8 3 4 7 6
1 4 7 6 5 8 3 2
1 6 7 4 3 8 5 2
Case 3:
No Answer
import java.util.Scanner;
public class 素数环 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int n = input.nextInt();
int[] rec = new int[n];
rec[0] = 1;
dfs(rec, 1);
}
static void dfs(int[] rec, int n) {
if (n == rec.length && suShu(rec[rec.length - 1] + rec[0])) {
for (int j = 0; j < rec.length; j++) {
System.out.print(rec[j]);
}
System.out.println();
return;
}
for (int i = 2; i <= rec.length; i++) {
if (check(rec, n, i)) {
rec[n] = i;
dfs(rec, n + 1);
rec[n] = 0;
}
}
}
static boolean check(int[] rec, int n, int i) {
for (int j = 0; j < n; j++) {
if (!suShu(rec[n - 1] + i) || rec[j] == i) {// 如果rec[n-1]+rec[n]不是质数,或者rec[]中的某一项==i返回false;
// 我一开始写的判断是
// if(rec[j]!=i&&suShu(rec[j] + rec[j+1])){在这里面rec[j]!=i是存在问题的,因为rec【0】=1;rec【1】=2;所以rec【3】=2;(3!=1)是true ;所以rec【3】=2
// return true;
// }
//这个非常精妙,他是反着思考的,
return false;
}
}
return true;
}
static boolean suShu(int x) {
for (int i = 2; i < x; i++) {
if (x % i == 0) {
return false;
}
}
return true;
}
}