#include <iostream>
using namespace std;
/*int main()
{
cout << "Hello World!" << endl;
int a = 0;
a = a + 2;
cout << a;
cout << "运行成功";
return 0;
}*/
#define MAXN 45
#define UNKNOWN -1
long f[MAXN];//定义一个long型数组
/*
long fib_c(int n)//fib_c(n)与f[n]相对应
{
if(f[n] == UNKNOWN)
f[n] = fib_c(n - 1) + fib_c(n - 2);//利用数组存储相关值,然后递归
return f[n];
}
long fib_c_driver(int n)
{
int i;
f[0] = 0;
f[1] = 1;
for(i = 2; i <= n; ++i)
f[i] = UNKNOWN;//从f[2]开始为每一个数赋标志值
return (fib_c(n));
}*/
long fib_dp(int n)
{
int i;
f[0] = 0;
f[1] = 1;
for(i = 2; i<= n; ++i)
f[i] = f[i - 1] + f[i - 2];
return f[n];
}
void fib_ultimate(int n)
{
int i;//用来记录fibonacci的个数
int back1 = 1;//记录前面第一个数
int back2 = 0;//记录前面第二个数
long next;//用来存放和
if(n == 0)
cout << back2 << " ";
if(n == 1)
cout << back2 << " ";
if(n >= 2)
{
cout << 0 << " ";
cout << 1 << " ";
for(i = 2; i <= n; ++i)
{
next = back1 + back2;
back2 = back1;
back1 = next;
cout << next << " ";
}
}
//return next;
}
int main()
{
cout << "Please Enter One num:" << endl;
int n;
cin >> n;
cout << "The fibonacci " << n <<" is:" << endl;
// long i = fib_c_driver(n);
//long i = fib_dp(n);
//long i = fib_ultimate(n);
//cout << i << endl;
fib_ultimate(n);
return 0;
}
关于斐波那契数列的几种解法
最新推荐文章于 2021-10-06 11:53:12 发布