簡體   English   中英

消除 C 中遞歸階乘函數中的冗余

[英]Eliminating redundancy in recursive factorial function in C

我們都知道階乘函數的這種實現:

double fact(double i) {
    if (i == 1 || i == 0) {
        return 1;
    } else
        return i * fact(i - 1);
}

我想消除冗余,因此執行時間會更低。 我嘗試使用查找數組,但無法正確執行。 如何消除冗余以使代碼運行得更快?

首先,您將冗余與遞歸混合:) 要消除,您可以使用 for 循環

result = 1;
for(int x=1; x<i; x++)
  result*=x

我在網上找到了這個方法,希望它有幫助。 這利用了動態規划。

Begin
   fact(int n):
      Read the number n
      Initialize
      i = 1, result[1000] = {0}
      result[0] = 1
      for i = 1 to n
         result[i] = I * result[i-1]
   Print result
End

有關更多信息,請參閱此鏈接 - https://www.tutorialspoint.com/cplusplus-program-to-find-factorial-of-a-number-using-dynamic-programming

如果你正在尋找遞歸的東西,根據我的說法,這是最好的。

int factorial(int n) {
    if (n>=1)
        return n*factorial(n-1);
    else
        return 1;
}

如果您發現其他內容,請告訴我們。

暫無
暫無

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

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