斐波那契数列实用解法

来源:互联网 发布:windows ntp客户端配置 编辑:程序博客网 时间:2024/06/07 02:57
// Fibonacci.cpp : Defines the entry point for the console application.
//时间复杂度为O(n),在计算中已经得到的中间项保存起来


#include "stdafx.h"
#include <iostream>
using namespace std;


long long Fibonacci(unsigned n) {
int result[2] = { 0,1 };
if (n < 2) {
return result[n];
}
long long fibNMinusOne = 1;
long long fibNMinusTwo = 0;
long long fibN = 0;
for (unsigned int i = 2; i <= n; i++) {
fibN = fibNMinusOne + fibNMinusTwo;
fibNMinusTwo = fibNMinusOne;
fibNMinusOne = fibN;
}
return fibN;
}
int main()
{
int n;
cin >> n;
cout << Fibonacci(n) << endl;
system("pause");
    return 0;
}
原创粉丝点击