斐波那契數列求解方法
阿新 • • 發佈:2019-01-12
求解斐波那契數列
1:遞迴演算法:
long long Fib(int n) {
if (n <= 1) return n;
return Fib(n - 1) + Fib(n - 2);
}
但這會導致大量重複的計算
2:記憶化搜尋/DP
long long num[100] = { 0 };
long long Fib(int n) {
if (n <= 1) return n;
if (num[n]) return num[n];
return num[n] = Fib(n - 1) + Fib(n - 2);
}
3:公式
long long Fib(int n) { double t = sqrt(5); return ( (pow((1 + t) / 2, n) - pow((1 - t) / 2, n)) ) / t; }
4:矩陣快速冪
#include <iostream> #include <algorithm> #include <string> #include <cstring> using namespace std; const int N = 2; long long tmp[N][N]; //矩陣乘法 void multi(long long a[][N], long long b[][N]){ memset(tmp, 0, sizeof (tmp)); for (int i = 0; i<2; i++) for (int j = 0; j<2; j++) for (int k = 0; k<2; k++) tmp[i][j] += a[i][k] * b[k][j]; for (int i = 0; i<2; i++) for (int j = 0; j<2; j++) a[i][j] = tmp[i][j]; } long long res[N][N]; //矩陣快速冪 void quickpow(long long a[][N], int n){ memset(res, 0, sizeof res); for (int i = 0; i<N; i++) res[i][i] = 1; while (n){ if (n & 1) multi(res, a); //res=res*a; multi(a, a); //a=a*a n >>= 1; } } //求解斐波那契數列 long long solve(int n) { long long m[2][2] = { 1, 1, 1, 0 }; quickpow(m, n); return res[0][1]; } int main() { cout << solve(10) << endl; return 0; }