分享一個刷題時候遇到的有意思的答案
原題要求計算斐波那契數列 某一項的值。
① 第一種是遞歸,這個大家都應該知道(有空我再補充)
② 看到網友 給出了一種巧妙的解法,最直接的區別是 只需要定義兩個變量即可 實現求解,算法複雜度分析我有空再補充。
// test.cpp: 定義控制檯應用程序的入口點。
//
#include "stdafx.h"
#include<iostream>
using namespace std;
int Fibonacci(int n);
int main()
{
cout<<Fibonacci(15);
system("pause");
return 0;
}
int Fibonacci(int n)
{
int f = 0, g = 1;
while (n--)
{
cout << "f=" << f << "\t";
cout << "g=" << g << "\n";
g += f;
f = g - f;
}
return g;
}
結果: