用java两种方法有n个人编号为1~n排成一个环从1号人开始从1到m报数报到m的人离开该环从下一个人开始继续从1到m报数报到m的人离开该环这样一直进行下去直到最终剩余p个人。从键盘输入n、m、p要求n=2、m=2、pn输出最终剩余的p个初始编号。
以下是使用Java编写的解决方案:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class JosephusProblem {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// 输入n、m、p
System.out.print("请输入总人数n:");
int n = scanner.nextInt();
System.out.print("请输入报数m:");
int m = scanner.nextInt();
System.out.print("请输入剩余人数p:");
int p = scanner.nextInt();
scanner.close();
// 初始化人员列表
List<Integer> people = new ArrayList<>();
for (int i = 1; i <= n; i++) {
people.add(i);
}
// 使用循环链表模拟报数过程
int currentIndex = 0; // 当前位置的索引
while (people.size() > p) {
currentIndex = (currentIndex + m - 1) % people.size();
people.remove(currentIndex);
}
// 输出最终剩余的p个初始编号
System.out.println("最终剩余的" + p + "个初始编号为:");
for (int i = 0; i < people.size(); i++) {
System.out.print(people.get(i));
if (i < people.size() - 1) {
System.out.print(", ");
}
}
}
}
使用该程序,你可以从键盘输入总人数n、报数m和剩余人数p,然后输出最终剩余的p个初始编号。请确保输入的n大于等于2、m大于等于2且p小于n
原文地址: https://www.cveoy.top/t/topic/hK6z 著作权归作者所有。请勿转载和采集!