用遞迴和非遞迴的方法輸出斐波那契數列的第n個元素(C語言實現)

來源:互聯網
上載者:User

標籤:can   非遞迴   mat   dir   lease   scanf   api   下標   wiki   

費波那契數列(意大利語:Successione di Fibonacci),又譯為費波拿契數斐波那契數列費氏數列黃金分割數列

在數學上,費波那契數列是以遞迴的方法來定義:

  • {\displaystyle F_{0}=0}
  • {\displaystyle F_{1}=1}
  • {\displaystyle F_{n}=F_{n-1}+F_{n-2}}(n≧2)

用文字來說,就是費波那契數列由0和1開始,之後的費波那契係數就是由之前的兩數相加而得出。首幾個費波那契係數是:

0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233……(OEIS中的數列A000045)

特別指出:0不是第一項,而是第零項。

 1 #include <stdio.h> 2  3 int fib1 (int n) ;    //非遞迴產生下標為n的斐波那契數列元素 4 int fib2 (int n) ;    //遞迴產生下標為n的斐波那契數列元素 5  6 int main () 7 { 8     int n ; 9     printf ("please input the index of fib:") ;10     scanf ("%d" , &n) ;11     printf ("the %d fib1 number is %d \n" , n , fib1(n)) ;12     printf ("the %d fib2 number is %d \n" , n , fib2(n)) ;13     return 0 ;14 }15 16 int fib1 (int n)17 {18     int i = 0 ;19     int a = 1 ;20     int b = 1 ;21     int result = 0 ;22     if (n <= 0)23     {24         return 0 ;25     }26     else if (n <= 2)27     {28         return 1 ;29     }30     else31     {32         for (i = 3 ; i <= n ; i ++)33         {34             result = a + b ;35             a = b ;36             b = result ;37         }38         return result ;39     }40 }41 42 int fib2 (int n)43 {44     if (n <= 0)45     {46         return 0 ;47     }48     else if (n <= 2)49     {50         return 1 ;    //遞迴終止條件51     }52     else53     {54         return fib2(n-1) + fib2(n-2) ;    //遞迴55     }56 }

 

用遞迴和非遞迴的方法輸出斐波那契數列的第n個元素(C語言實現)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.