方法一:很容易想到的解法是直接使用遞歸。
C++代碼:
#include "stdafx.h" #include <iostream> using namespace std; long long Fibonacci(unsigned int n) { if (n == 0) { return 0; } if (n == 1) { return 1; } return Fibonacci(n-1) + Fibonacci(n-2); } int _tmain(int argc, _TCHAR* argv[]) { unsigned int n = 10; cout << Fibonacci(n) << endl; system("pause"); return 0; } #include "stdafx.h" #include <iostream> using namespace std; long long Fibonacci(unsigned int n) { if (n == 0) { return 0; } if (n == 1) { return 1; } return Fibonacci(n-1) + Fibonacci(n-2); } int _tmain(int argc, _TCHAR* argv[]) { unsigned int n = 10; cout << Fibonacci(n) << endl; system("pause"); return 0; }
缺點:很顯然效率很低,因為存在重復計算的問題。
方法二:改進方法是將已經得到的數列中間項保存起來,下次使用時直接查找即可,避免重復計算。
C++代碼:
#include "stdafx.h" #include <iostream> using namespace std; long long Fibonacci(unsigned int n) { if (n == 0) { return 0; } if (n == 1) { return 1; } long long one = 0; long long two = 1; long long result = 0; for (unsigned int i=2; i<=n; i++) { result = one + two; one = two; two = result; } return result; } int _tmain(int argc, _TCHAR* argv[]) { unsigned int n = 100; cout << Fibonacci(n) << endl; system("pause"); return 0; } #include "stdafx.h" #include <iostream> using namespace std; long long Fibonacci(unsigned int n) { if (n == 0) { return 0; } if (n == 1) { return 1; } long long one = 0; long long two = 1; long long result = 0; for (unsigned int i=2; i<=n; i++) { result = one + two; one = two; two = result; } return result; } int _tmain(int argc, _TCHAR* argv[]) { unsigned int n = 100; cout << Fibonacci(n) << endl; system("pause"); return 0; }