以下是一个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();

        if (n < 2 || m < 2 || p >= n) {
            System.out.println("输入不符合要求!");
            return;
        }

        List<Integer> people = new ArrayList<>();
        for (int i = 1; i <= n; i++) {
            people.add(i);
        }

        int currentIndex = -1;
        while (people.size() > p) {
            int count = 0;
            while (count < m) {
                currentIndex = (currentIndex + 1) % people.size();
                count++;
            }
            people.remove(currentIndex);
            currentIndex--;
        }

        System.out.println("最终剩余的" + p + "个初始编号:");
        for (int i = 0; i < people.size(); i++) {
            System.out.println(people.get(i));
        }
    }
}

你可以运行上述程序,并按照提示输入n、m和p的值,程序将输出最终剩余的p个初始编号。注意,输入的n、m和p必须满足题目要求,否则程序会给出错误提示


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

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