關於遞迴次數的計算

來源:互聯網
上載者:User

標籤:

有這樣一個題目:

遞迴函式:

 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 }

運行:

驗證正確了

 

對於這種計算遞迴調用次數一定要思路清晰,最好是將所有的遞迴調用都遞迴到遞迴出口的

地方再統一進行遞迴出口的調用,這樣不容易造成紊亂,個人意見,僅供參考。

關於遞迴次數的計算

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.