import java.util.Scanner; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); int n = in.nextInt(); long minAbs = Long.MAX_VALUE; int bestX = -1; int bestY = -1; List<Integer> xList = new ArrayList<>(); xList.add(1); for (int x = 3; x <= 20; x++) { xList.add(x); } for (int x : xList) { long fact = 1; for (int i = 2; i <= x; i++) { fact *= i; } long f = fact - 1; long currentAbs; int currentY; if (x == 1) { currentAbs = n; currentY = 1; } else { List<Integer> candidates = new ArrayList<>(); if (f > n) { candidates.add(1); } else { int y0 = (int) (n / f); candidates.add(y0 - 1); candidates.add(y0); candidates.add(y0 + 1); } List<Integer> validCandidates = new ArrayList<>(); for (int y : candidates) { if (y > 0 && y != 2) { validCandidates.add(y); } } if (validCandidates.isEmpty()) { validCandidates.add(1); validCandidates.add(3); } long localMinAbs = Long.MAX_VALUE; int localBestY = -1; for (int y : validCandidates) { long abs = Math.abs(f * y - n); if (abs < localMinAbs) { localMinAbs = abs; localBestY = y; } else if (abs == localMinAbs) { if (y < localBestY) { localBestY = y; } } } currentAbs = localMinAbs; currentY = localBestY; } if (currentAbs < minAbs || (currentAbs == minAbs && (x < bestX || (x == bestX && currentY < bestY)))) { minAbs = currentAbs; bestX = x; bestY = currentY; } } System.out.println(bestX + " " + bestY); } }
https://www.nowcoder.com/discuss/727521113110073344
思路:
- 输入处理:读取输入的整数 𝑛。
- 候选生成:生成可能的 𝑥 值列表,跳过 𝑥=2。
- 阶乘计算:计算每个 𝑥 的阶乘,并生成对应的候选 𝑦 值。
- 过滤和选择:过滤无效候选值,选择使表达式绝对值最小的 𝑦。
- 更新最优解:比较所有候选解,找到并输出最优的 𝑥 和 𝑦。