约瑟夫环问题 Java 实现 - 循环报数淘汰算法
以下是一个 Java 程序,实现了约瑟夫环问题:\n\njava\nimport java.util.ArrayList;\nimport java.util.List;\nimport java.util.Scanner;\n\npublic class JosephusProblem {\n public static void main(String[] args) {\n Scanner scanner = new Scanner(System.in);\n System.out.print("请输入n的值:");\n int n = scanner.nextInt();\n System.out.print("请输入m的值:");\n int m = scanner.nextInt();\n System.out.print("请输入p的值:");\n int p = scanner.nextInt();\n\n if (n < 2 || m < 2 || p >= n) {\n System.out.println("输入不符合要求!");\n return;\n }\n\n List<Integer> people = new ArrayList<>();\n for (int i = 1; i <= n; i++) {\n people.add(i);\n }\n\n int currentIndex = -1;\n while (people.size() > p) {\n int count = 0;\n while (count < m) {\n currentIndex = (currentIndex + 1) % people.size();\n count++;\n }\n people.remove(currentIndex);\n currentIndex--;\n }\n\n System.out.println("最终剩余的" + p + "个初始编号:");\n for (int i = 0; i < people.size(); i++) {\n System.out.println(people.get(i));\n }\n }\n}\n\n\n你可以运行上述程序,并按照提示输入 n、m 和 p 的值,程序将输出最终剩余的 p 个初始编号。注意,输入的 n、m 和 p 必须满足题目要求,否则程序会给出错误提示。
原文地址: https://www.cveoy.top/t/topic/psjP 著作权归作者所有。请勿转载和采集!