2、约瑟夫环问题有n个人编号为1~n排成一个环从1号人开始从1到m报数报到m的人离开该环从下一个人开始继续从1到m报数报到m的人离开该环这样一直进行下去直到最终剩余p个人。从键盘输入n、m、p要求n=2、m=2、1=pn输出最终剩余的p个初始编号。例如:输入n、m、p依此为4、3、2则输出为1和4。用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("最终剩余的编号为:");
for (int i = 0; i < people.size(); i++) {
System.out.print(people.get(i) + " ");
}
}
}
运行程序后,根据提示依次输入总人数n、报数的数字m和最终剩余人数p,程序会输出最终剩余的p个初始编号
原文地址: https://www.cveoy.top/t/topic/hMop 著作权归作者所有。请勿转载和采集!