標籤:
有這樣一個題目:
遞迴函式:
1 int x(int n) 2 { 3 if(n<=3) 4 { 5 return 1; 6 } 7 else 8 { 9 return x(n-2)+x(n-4)+1;10 }11 }
計算x(x(8))遞迴調用次數。
大多數可能覺得這是一個很簡單的題目,的確很簡單。
但是要想在沒有編譯器的情況下正確的算出這個遞迴
調用次數其實還是需要點耐心.
x(x(8))我們先計算x(8),我們用count=0計數遞迴調用次數
1.x(8)=x(6)+x(4)+1 count=1;
2.x(6)=x(4)+x(2)+1,x(4)=x(2)+x(0)+1 x(8)=x(4)+2*x(2)+x(0)+3 count=3;
3.x(4)=x(2)+x(0)+1 x(8)=3*x(2)+2*x(0)+4 count=4
4.x(2)=1,x(0)=1; x(8)=9 count=9
再計算x(9)
1.x(9)=x(7)+x(5)+1 count=10
2.x(7)=x(5)+x(3)+1,x(5)=x(3)+x(1)+1 x(9)=x(5)+2*x(3)+x(1)+3 count=12
3.x(5)=x(3)+x(1)+1 x(9)=3*x(3)+2*x(1)+4 count=13
4.x(3)=1 x(1)=1 x(9)=3+2+4=9 count=18
接下來我們再用程式驗證一下:
1 #include <iostream> 2 using namespace std; 3 4 static int count=0; 5 6 int x(int n) 7 { 8 if(n<=3) 9 {10 count++;11 return 1;12 }13 else14 {15 count++;16 return x(n-2)+x(n-4)+1;17 }18 }19 20 int main(void)21 { 22 cout<<"x(x8)="<<x(x(8))<<endl;23 cout<<"count="<<count<<endl;24 system("pause");25 return 0;26 }
運行:
驗證正確了
對於這種計算遞迴調用次數一定要思路清晰,最好是將所有的遞迴調用都遞迴到遞迴出口的
地方再統一進行遞迴出口的調用,這樣不容易造成紊亂,個人意見,僅供參考。
關於遞迴次數的計算