有n个人编号为1~n排成一个环从1号人开始从1到m报数报到m的人离开该环从下一个人开始继续从1到m报数报到m的人离开该环这样一直进行下去直到最终剩余p个人。从键盘输入n、m、p要求n>=2、m>=2、p<n输出最终剩余的p个初始编号。用Java编写
import java.util.ArrayList; import java.util.List; import java.util.Scanner;
public class JosephusCircle { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("请输入总人数n:"); int n = scanner.nextInt(); System.out.println("请输入报数m:"); int m = scanner.nextInt(); System.out.println("请输入最终剩余人数p:"); int p = scanner.nextInt();
if (n < 2 || m < 2 || p >= n) {
System.out.println("输入不符合要求");
return;
}
List<Integer> circle = new ArrayList<>();
for (int i = 1; i <= n; i++) {
circle.add(i);
}
int index = 0;
while (circle.size() > p) {
index = (index + m - 1) % circle.size();
circle.remove(index);
}
System.out.println("最终剩余的" + p + "个初始编号为:");
for (int i = 0; i < p; i++) {
System.out.print(circle.get(i) + " ");
}
}
原文地址: https://www.cveoy.top/t/topic/hG4W 著作权归作者所有。请勿转载和采集!