请用java语言编写一段代码:构造一个长度为n的排列,其中有k个好元素,且任意两个好元素都不相邻。输入一个正整数n,希望找到一对正整数x和y,满足|x! × y -y - n|最小,其中x和y都不等于2,且!表示阶乘,输出正整数x和y
时间: 2024-05-15 13:15:38 浏览: 45
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int k = scanner.nextInt();
List<Integer> list = new ArrayList<>();
for (int i = 1; i <= n; i++) {
if (i <= k * 2) {
list.add(i % 2 == 1 ? i / 2 + 1 + k : i / 2 + k);
} else {
list.add(i);
}
}
int x = 0, y = 0;
long min = Long.MAX_VALUE;
for (int i = 3; i <= n; i++) {
if (i == 2) continue;
long factorial = factorial(i);
for (int j = 2; j <= n; j++) {
if (j == 2 || j == i) continue;
long value = factorial * j - j - n;
if (Math.abs(value) < min) {
min = Math.abs(value);
x = i;
y = j;
}
}
}
System.out.println(x + " " + y);
}
private static long factorial(int n) {
long res = 1;
for (int i = 2; i <= n; i++) {
res *= i;
}
return res;
}
}
```
阅读全文