public class JosephProblem { public static int joseph(int n) { if (n == 1) { return 0; } else { return (joseph(n - 1) + 2) % n; } } public static int joseph(int n, int k) { int s = 0; for (int i = 2; i <= n; i++) { s = (s + k) % i; } return s + 1; } public static int joseph(int n, int m, int k) { int p = 1; int t = 0; for (int i = 2; i <= n; i++) { p = (p * m) % i; } for (int i = 1; i <= n; i++) { t = (t + k * p) % i; } return t + 1; } public static void main(String[] args) { int n = 10; int k = 3; int m = 2; System.out.println("The solution to Joseph problem with n=" + n + " is " + joseph(n)); System.out.println("The solution to Joseph problem with n=" + n + " and k=" + k + " is " + joseph(n, k)); System.out.println("The solution to Joseph problem with n=" + n + ", m=" + m + " and k=" + k + " is " + joseph(n, m, k)); } }有什么错误
时间: 2024-01-28 08:03:31 浏览: 88
代码看起来没有明显的错误,但需要注意的是:在joseph函数中,当n等于1时,返回的是0,但这并不符合题目要求,因为题目中的编号是从1开始的。应该将返回值加1才是正确答案。因此,应该将第1个joseph函数的返回语句改为:
```
return (joseph(n - 1) + k) % n;
```
这样才能得到正确的结果。
阅读全文