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);

        // 从键盘输入n、m、p
        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 count = 0;
        // 当前位置,用于记录报数的位置
        int current = 0;

        // 循环直到剩余p个人
        while (people.size() > p) {
            // 报数
            count++;
            // 如果报到m,移除该人
            if (count == m) {
                people.remove(current);
                count = 0;
            } else {
                // 否则,移动到下一个位置
                current++;
            }

            // 如果当前位置已经超过了人数,重置为0
            if (current == people.size()) {
                current = 0;
            }
        }

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

使用示例: 输入:

请输入n:10
请输入m:3
请输入p:2

输出:

2
5
``
有n个人编号为1~n排成一个环从1号人开始从1到m报数报到m的人离开该环从下一个人开始继续从1到m报数报到m的人离开该环这样一直进行下去直到最终剩余p个人。从键盘输入n、m、p要求n=2、m=2、pn输出最终剩余的p个初始编号。用Java编写

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

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