[英]When are the multiplications done in this recursive factorial function?
我正在嘗試了解以下問題:
public class Main {
public static int fact(int n){
if (n == 0){
return 1;
}else{
return n * fact(n - 1);
}
}
public static void main(String[] args){
System.out.print(fact(5));
}
}
當編譯器執行並return n * fact(n - 1);
它實際上是乘以n
還是僅在達到基本情況后才這樣做,然后再乘以存儲在堆棧中的所有值?
注意,我對這種遞歸編碼方式還是陌生的。
查看以什么順序執行乘法的好方法,將n * fact(...)
替換為mult(n, fact(...))
,其中mult
是您編寫的方法,需要兩個數字並返回其乘積。 然后,您可以在mult
添加一些輸出打印,並查看調用的順序。
public class FactorialExample {
// The new mult method.
private static int mult( final int x, final int y ) {
System.out.println( "Multiplying "+x+" and "+y+"." );
return x * y;
}
public static int fact(int n){
if (n == 0){
return 1;
}else{
return mult(n, fact(n - 1)); // using the new mult method
}
}
public static void main(String[] args){
System.out.print(fact(5));
}
}
這將產生以下輸出:
Multiplying 1 and 1.
Multiplying 2 and 1.
Multiplying 3 and 2.
Multiplying 4 and 6.
Multiplying 5 and 24.
120
回想一下,左加數是對應於n
那個,並且對fact
的第一次調用具有最大的價值。 因此,遞歸調用fact(4)
必須首先完成(產生24
),然后將5
與24
相乘。
(注意: 編譯器不是評估fact
的程序;程序本身會這樣做)。
程序遇到語句時
n * fact(n - 1)
它將通過調用fact
並將n - 1
作為參數來隔離計算fact(n - 1)
。 一旦該函數完成運行並返回,它將具有一個值,然后可以乘以n
。 這樣做的凈效果是,直到達到基本情況之后才執行乘法運算,此時存儲在堆棧中的n
的值將全部相乘在一起。 您可以在行上放置一個斷點來查看
return n * fact(n - 1);
並觀察該程序展開遞歸以計算總價值。
希望這可以幫助!
1. java tries to output unknown value, so java execute fact with N = 5
2. tries to multiple 5 by value, which is unknown, it executes fact with N=5-1
3. tries to multiple 4 by value ..... N=3
4. tries to multiple 3 by value ..... N=2
5. tries to multiple 2 by value ..... N=1
6. tries to multiple 1 by value ..... N=0
7. returns 1 and go back to 6th item
8. 1*1 = 1 and go back to 5th item
9. 2*1 = 2 and go back to 4th item
10. 3*2 = 6 and go back to 3rd item
11. 4*6 = 24 and go back to 2nd item
12. 5*24 = 120 and return to 1st item
13. display 120
一旦fact(n - 1)
得到評估,它將乘以n
和fact(n - 1)
fact(n - 1)
直到您遇到基本情況時才如此)。
遞歸的fact()
調用被鏈接在一起,直到最后一個返回。
這是簡單的遞歸。 與任何遞歸一樣,它首先深入到基本情況(使用堆棧),然后進行乘法(在堆棧展開過程中)
因此,在您的示例(即fact(5))的情況下會發生什么
fact(5) --> 5 * fact(4) // Here another recursive call is made to calculate fact(4)
fact(4) --> 4 * fact(3)//Here another recursive call is made to calculate fact(3)
.
.
.
fact(1) --> 1 * fact(0)// fact(0) is 1 as per your code
從這一點開始,堆棧展開,並且每個fact(n)
現在都由其簡化版本表示。 最后, fact(5) --> 5 * fact(4)
轉換為fact(5) --> 5 * 4 * 3 *2 *1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.