下面是使用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 = -1;
        
        while (people.size() > p) {
            // 计算下一个要离开的人的位置
            index = (index + m) % people.size();
            // 移除离开的人
            people.remove(index);
            // 更新当前位置
            index--;
        }
        
        System.out.println("最终剩余的人:" + people);
    }
}

运行程序后,根据提示输入人数n、报数m和最终剩余人数p,程序将输出最终剩余的p个初始编号


原文地址: https://www.cveoy.top/t/topic/hK9b 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录