c++ - 将递归函数重写为非递归函数

标签 c++ recursion

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

}

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

最佳答案

我认为您的问题中确实应该是 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),我将它作为练习留给您修改代码。

关于c++ - 将递归函数重写为非递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33132673/

相关文章:

c++ - 使用指定的初始值设定项进行模板参数推导

c++ - 为什么UDP服务器上的UDP客户端端口会发生变化

java - 数组的 ArrayList 每次都会被覆盖

haskell - 深度 Haskell 递归中异常的替代方案是什么?

c - 中点集成优化

c++ - 我可以将 unsigned char 转换为 char ,反之亦然吗?

c++ - native C++ 属性的可移植性

c++ - Xcode 中 wxWidgets 项目中的 undefined symbol

javascript - 如何递归地螺旋遍历矩阵 - javascript

c - 递归 - 链表中倒数第 n 个元素