下面是用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 count = 0;
        int index = 0;
        while (people.size() > p) {
            count++;
            if (count == m) {
                people.remove(index);
                count = 0;
            } else {
                index++;
            }
            if (index == people.size()) {
                index = 0;
            }
        }
        
        System.out.print("最终剩余的" + p + "个初始编号为:");
        for (int i = 0; i < people.size(); i++) {
            if (i != people.size() - 1) {
                System.out.print(people.get(i) + "和");
            } else {
                System.out.println(people.get(i));
            }
        }
    }
}

你可以运行这段代码,并根据提示输入n、m和p的值,程序将输出最终剩余的p个初始编号

用java实现约瑟夫环问题有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。

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

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