引入矩陣冪次乘法
class Solution {
public:
int fib(int n) {
if(n < 1) return 0;
if(n < 3) return 1;
vector<vector<int>> begin{{1,1}};
vector<vector<int>> base{{1,1},{1,0}};
vector<vector<int>> res = matrix_mul(begin,base,n-3);
return res[0][0]+res[0][1];
}
vector<vector<int>> matrix_mul(vector<vector<int>> res,vector<vector<int>> &base,int power){
for(;power != 0;power = power>>1){
if(power&1){
res = muli_matrix(res,base);
}
base = muli_matrix(base,base);
}
return res;
}
vector<vector<int>> muli_matrix(vector<vector<int>> m1,vector<vector<int>> m2){
int row = m1.size(),col = m2[0].size(),num = m1[0].size();
vector<vector<int>> res(row,vector<int>(col,0));
for(int i = 0;i < row;i++){
for(int j = 0;j < col;j++){
for(int k = 0;k < num;k++){
res[i][j] += m1[i][k]*m2[k][j];
}
}
}
return res;
}
};
int main(){
Solution *s = new Solution();
int res = s->fib(6);
cout << res << endl;
}