生成斐波纳契数列
斐波纳契数列如下
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
广告