Method 1: It is easy to think of using recursion directly.
C ++ code:
#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;}
Disadvantage: it is obvious that the efficiency is very low because of repeated computing problems.
Method 2: the improved method is to save the intermediate items of the obtained series and directly search for them next time to avoid repeated computation.
C ++ code:
#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;}