生成斐波那契數列
斐波那契數列是這樣的:
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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP