生成斐波納契數列
斐波納契數列如下
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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP