我有使用递归的josephus问题的代码,但我不太明白它可以解释给我

编程入门 行业动态 更新时间:2024-10-24 07:23:42
本文介绍了我有使用递归的josephus问题的代码,但我不太明白它可以解释给我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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问题的代码,但我不太明白它可以解释给我

本文发布于:2023-11-30 20:30:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1651390.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:递归   给我   不太   我有   但我

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!