有n个人编号为1~n排成一个环从1号人开始从1到m报数报到m的人离开该环从下一个人开始继续从1到m报数报到m的人离开该环这样一直进行下去直到最终剩余p个人。从键盘输入n、m、p要求n=2、m=2、pn输出最终剩余的p个初始编号。请用java语言编写
以下是用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);
System.out.print("请输入n的值:");
int n = scanner.nextInt();
System.out.print("请输入m的值:");
int m = scanner.nextInt();
System.out.print("请输入p的值:");
int p = scanner.nextInt();
List<Integer> people = new ArrayList<>();
for (int i = 1; i <= n; i++) {
people.add(i);
}
int index = 0;
while (people.size() > p) {
index = (index + m - 1) % people.size();
people.remove(index);
}
System.out.println("最终剩余的" + p + "个初始编号为:");
for (int i = 0; i < p; i++) {
System.out.print(people.get(i) + " ");
}
}
}
在上述代码中,我们首先从键盘输入n、m、p的值。然后创建一个List来存储初始编号。接下来,使用一个循环从1到n依次添加初始编号到List中。
然后,我们使用一个循环来模拟报数并移除相应的人员。在每一次循环中,我们计算出下一个要离开的人员的索引,然后从List中移除该人员。这里使用了取模运算符来处理环形队列。
最后,我们输出剩余的p个初始编号
原文地址: https://www.cveoy.top/t/topic/hN9m 著作权归作者所有。请勿转载和采集!