生成斐波那契數列


斐波那契數列是這樣的:

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

在此數列中,第 n 個數是(n-1)個數和(n-2)個數的和。

要生成,我們可以使用遞迴法,但在動態規劃中,方法很簡單,它可以把所有的斐波那契數儲存在一個表格中,並透過該表格輕鬆地生成該數列中的下一個數。

輸入和輸出

Input:
Take the term number as an input. Say it is 10
Output:
Enter number of terms: 10
10th fibinacci Terms: 55

演算法

genFiboSeries(n)

輸入:最大項數。

輸出 −第 n 個斐波那契數.

Begin
   define array named fibo of size n+2
   fibo[0] := 0
   fibo[1] := 1

   for i := 2 to n, do
      fibo[i] := fibo[i-1] + fibo[i-2]
   done
   return fibo[n]
End

示例

#include<iostream>
using namespace std;

int genFibonacci(int n) {
   int fibo[n+2];          //array to store fibonacci values

   // 0th and 1st number of the series are 0 and 1
   fibo[0] = 0;
   fibo[1] = 1;

   for (int i = 2; i <= n; i++) {
      fibo[i] = fibo[i-1] + fibo[i-2];    //generate ith term using previous two terms
   }
   return fibo[n];
}

int main () {
   int n;
   cout << "Enter number of terms: "; cin >>n;
   cout << n<<" th Fibonacci Terms: "<<genFibonacci(n)<<endl;
}

輸出

Enter number of terms: 10
10th Fibonacci Terms: 55

更新於:2020-6-16

2 千次瀏覽

開啟你的職業生涯

完成課程後獲得認證

開始
廣告
© . All rights reserved.