将递归函数重写为非递归函数(Rewriting a recursive function to a non

编程入门 行业动态 更新时间:2024-10-24 06:25:24
递归函数重写为非递归函数(Rewriting a recursive function to a non-recursive function) int foo(int x) { if (x >= 0) { return (x - 1) + 2 * foo(x - 1); } else { return 1; } }

嗨,我需要重写这个函数,使它没有递归。 我尝试用数学方法解决这个问题,但无济于事。 我是编程新手,所以任何帮助都将不胜感激。 提前致谢!

int foo(int x) { if (x >= 0) { return (x - 1) + 2 * foo(x - 1); } else { return 1; } }

Hi, I need to rewrite this function such that it will be free of recursion. I tried solving this mathematically, but to no avail. I am new to programming, so any help will be much appreciated. Thanks in advance!

最满意答案

我认为你的问题确实应该是if(x>0) 。

然后检查你的函数,我们看到foo(0)=1 ,否则foo(x)=(x-1)+2*foo(x-1) 。 因此foo(x)仅取决于foo(x-1) 。 因此,您可以简单地使用迭代来推进结果

int foo(int x) { auto result=1; // result if x=0 for(int n=0; n!=x; ++n) // increment result to desired x result=n+2*result; // corresponds to (x-1)+2*foo(x-1) in original return result; }

如果它确实是if(x>=0) ,我将它作为练习留给你调整代码。

I assume that it really should be if(x>0) in your question.

Then examining your function, we see that foo(0)=1 and otherwise that foo(x)=(x-1)+2*foo(x-1). Thus foo(x) only depends on foo(x-1). So, you can simply use an iteration to progress the result

int foo(int x) { auto result=1; // result if x=0 for(int n=0; n!=x; ++n) // increment result to desired x result=n+2*result; // corresponds to (x-1)+2*foo(x-1) in original return result; }

If it really was if(x>=0) instead, I leave it as an exercise to you to adapt the code.

更多推荐

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

发布评论

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

>www.elefans.com

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