我有使用递归的josephus问题的代码,但我不太明白它可以解释给我 [英] I have the code for the josephus problem using recursion but I don't quite understand it can some one explain to me

查看:64
本文介绍了我有使用递归的josephus问题的代码,但我不太明白它可以解释给我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你可以在约瑟夫斯问题 - 维基百科 [ ^ ]我已经知道不使用递归的解决方案,但我真的想知道这个是如何工作的。在这种情况下,我正在使用第2步,这意味着当它删除n(数字)然后它跳转n + 1然后删除n + 2.



< b>我尝试了什么:



you can see the josephus problem at Josephus problem - Wikipedia[^] and i already know the solution that doesn't use recursion but i really want to know how this one works. in this case i'm using the step 2 which means when it deletes n(a number) then it jumps n+1 and then deletes n+2.

What I have tried:

<pre>
#include <stdio.h>
#include <stdlib.h>
int winner(int n){
if (n==1)
    return 1;
else
    return (winner(n-1)+1)%n+1;
}
int main()
{
    int n;
    scanf("%d", &n);
printf("%d", winner(n));
    return 0;
}

推荐答案

有什么要解释的?要么你理解递归,要么你需要学习它。

学习递归很简单:只学习递归。



使用n的特定值调用wins方法。如果它不是一个(即获胜位置),它用n减1调用自己,并使用其中的结果来计算获胜位置。

如果你理解递归是如何工作的,那很明显。



所以抓住调试器,然后按照代码进行操作。值得快速改变一下。更改此:

What's to explain? Either you understand recursion, or you need to learn it.
To learn recursion is simple to do: just learn recursion.

The winner method is called with a specific value for n. If it isn't one (i.e. the winning position) it calls itself with n minus one, and uses the result from that to calculate teh winning position.
If you understand how recursion works, it's pretty clear.

So grab the debugger, and follow the code through. It's worth making a quick change first. Change this:
return (winner(n-1)+1)%n+1;



到此:


to this:

{
int res = winner(n-1);
res = res + 1;
res = res % n + 1;
return res;
}

这样,您可以完全按照每个阶段完成(并返回)的操作。

That way, you can follow exactly what is being done (and returned) at each stage.


这篇关于我有使用递归的josephus问题的代码,但我不太明白它可以解释给我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆