矩陣乘法 求斐波那契數列
阿新 • • 發佈:2019-02-12
問題的求解就變成的解決,而冪的求可用二分法來求
#include <cstdio> #include <cstdlib> #include <iostream> #include <string.h> #include <algorithm> using namespace std; struct matrix { int a[2][2]; }; matrix mul(matrix &x, matrix &y) { matrix res; int sum; for(int i=0; i<2; i++) for(int j=0; j<2; j++) { sum = 0; for(int k=0; k<2; k++) sum += x.a[i][k]*y.a[k][j]; res.a[i][j] = sum; } x = res; return x; } matrix pow(matrix x, long e) { matrix ans, temp; if(e == 0) { ans.a[0][0]=1; ans.a[0][1]=0; ans.a[1][0]=0; ans.a[1][1]=1; return ans; } if(e == 1) return x; temp = pow(x, e>>1); ans = mul(temp, temp); if(e&1) ans = mul(ans,x); return ans; } int main() { int n; matrix ans; matrix base ={{1,1,1,0}}; while(~scanf("%d", &n)) { if(!n) printf("0\n"); else { ans = pow(base, n-1); printf("%d\n",ans.a[0][0]); } } system("pause"); return 0; }