簡體   English   中英

將遞歸函數重寫為非遞歸函數

[英]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;
    }

}

嗨,我需要重寫這個函數,這樣它就不會有遞歸。 我嘗試用數學方法解決這個問題,但無濟於事。 我是編程新手,所以任何幫助都將不勝感激。 提前致謝!

我認為你的問題確實應該是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) ,我將它作為練習留給你調整代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM