public class Main {
public static void main(String[] args) {
int[] digits = {1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] permutation = new int[9];
boolean[] used = new boolean[10]; // 初始值为false,用于标记数字是否已被使用
// 使用回溯生成满足条件的9位数
generateUniqueNumber(digits, permutation, used, 0);
}
// 递归生成满足条件的9位数
private static void generateUniqueNumber(int[] digits, int[] permutation, boolean[] used, int index) {
if (index == 9) {
// 检查是否满足整除条件
if (isDivisible(permutation)) {
for (int digit : permutation) {
System.out.print(digit);
}
System.out.println();
}
return;
}
// 生成排列组合
for (int i = 0; i < digits.length; i++) {
if (!used[digits[i]]) {
permutation[index] = digits[i];
used[digits[i]] = true;
generateUniqueNumber(digits, permutation, used, index + 1);
used[digits[i]] = false;
}
}
}
// 检查是否满足整除条件
private static boolean isDivisible(int[] permutation) {
for (int i = 1; i <= permutation.length; i++) {
int number = 0;
for (int j = 0; j < i; j++) {
number = number * 10 + permutation[j];
}
if (number % i != 0) {
return false;
}
}
return true;
}
}
求一个9位数,该数的每一位均是1-9之间的数,但是每位上的数字各不相同.最后使得这个9位数从高位开始,前一位能被1整除,前两位能被2整除,前三位能被3整除,前四位能被4整除……一直到整个9
最新推荐文章于 2024-09-15 19:46:31 发布