生成斐波那契数列
斐波那契数列是这样的:
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