題組內容
四、以下是 1 個函數(function),用類似 C(C-like)的語言來表示。假設輸入的參數
n 都是正整數,請回答下列問題:(10 分)
⑵將這個函數改成不用 recursive call 的寫法。 1) int f(n) { 2) if (n > 1) 3) return n * f(n – 1); 4) else 5) return 1; 6) }
詳解 (共 1 筆)
詳解
要將這個遞迴函數改成非遞迴的寫法,我們需要理解這個函數實際上在計算什麼。根據你提供的函數,它實際上是在計算 n 的階乘(factorial),而不是之前的和。
函數的分析
給定函數:
c
複製程式碼
int f(int n) {
if (n > 1)
return n * f(n - 1);
else
return 1;
}
這個函數計算 n 的階乘,記作 n!。階乘的定義是:
n!=n×(n−1)×(n−2)×…×1n! = n \times (n-1) \times (n-2) \times \ldots \times 1n!=n×(n−1)×(n−2)×…×1
非遞迴版本
我們可以使用迴圈來實現這個計算。以下是非遞迴版本的 f 函數:
c
複製程式碼
int f(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
代碼解釋
- 初始化 result:我們初始化一個變數 result 為 1,這是因為任何數的階乘都至少包含 1。
- 迴圈計算:使用一個從 1 遍歷到 n 的迴圈,將每個數字與 result 相乘。
- 返回結果:迴圈結束後,result 就是 n!。
完整程式碼
c
複製程式碼
#include <stdio.h>
int f(int n) { int result = 1; for (int i = 1; i <= n; i++) { result *= i; } return result; }
int main() { int n = 5; // 示例數值 printf("f(%d) = %d\n", n, f(n)); // 應輸出 f(5) = 120 return 0; }
總結
這個非遞迴版本的 f 函數通過迴圈來計算 n 的階乘,避免了遞迴調用帶來的呼叫堆疊深度問題,更加高效且容易理解。