首頁  >  文章  >  後端開發  >  在C語言中編寫的斐波那契數列程序

在C語言中編寫的斐波那契數列程序

WBOY
WBOY轉載
2023-09-05 18:53:061051瀏覽

在C語言中編寫的斐波那契數列程序

給定'n'個數字,任務是產生從0到n的斐波那契數列,其中整數的斐波那契數列形式為

0, 1, 1, 2, 3, 5, 8, 13, 21, 34

其中,整數0和1將有固定的空格,然後加上兩位數字,例如,

將原文翻譯為中文後,保留HTML程式碼如下:

其中,整數0和1將有固定的空格,然後加入兩位數字,例如,

0+1=1(3<sup>rd</sup> place)
1+1=2(4<sup>th</sup> place)
2+1=3(5<sup>th</sup> place) and So on

斐波那契數列的序列F (n)將具有定義為−的遞迴關係。

Fn = Fn-1 + Fn-2
Where, F(0)=0 and F(1)=1 are always fixed

可以使用多種方法來產生斐波那契數列−

遞歸方法 − 在這種方法中,函數在每個整數值之後都會調用自身。它簡單易行,但會導致指數級的時間複雜度,使得這種方法不夠有效。

使用for迴圈 − 透過使用for迴圈來產生斐波那契數列,可以將時間複雜度降低到O(n),使得這種方法更加有效。

範例

Input-: n=10
Output-: 0 1 1 2 3 5 8 13 21 34

演算法

Start
Step 1 -> Declare function for Fibonacci series
   Void Fibonacci(int n)
      Declare variables as int a=0,b=1,c,i
      Print a and b
      Loop For i=2 and i<n and ++i
         Set c=a+b
         Print c
         Set a=b
         Set b=c
      End
Step 2 -> In main()
   Declare int as 10
   Call Fibonacci(n)
Stop

Example

的中文翻譯為:

範例

#include<stdio.h>
void fibonacci(int n){
   int a=0,b=1,c,i;
   printf("fibonacci series till %d is ",n);
   printf("</p><p>%d %d",a,b);//it will print 0 and 1
   for(i=2;i<n;++i) //loop starts from 2 because 0 and 1 are the fixed values that series will take{
      c=a+b;
      printf(" %d",c);
      a=b;
      b=c;
   }
}
int main(){
   int n=10;
   fibonacci(n);
   return 0;
}

輸出

fibonacci series till 10 is
0 1 1 2 3 5 8 13 21 34

以上是在C語言中編寫的斐波那契數列程序的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除