矩阵快速幂模板及其应用到Fibonacci斐波那契数列计算
模板例题poj3070
#include<iostream>
using namespace std;
const int mod = 10000;
struct matrix {
int m[2][2];
}ans;
matrix base = { 1, 1, 1, 0 };
matrix multi(matrix a, matrix b) {
matrix tmp;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
tmp.m[i][j] = 0;
for (int k = 0; k < 2; k++)
tmp.m[i][j] = (tmp.m[i][j] + a.m[i][k] * b.m[k][j]) % mod;
}
}
return tmp;
}
int matrix_pow(matrix a, int n) {
ans.m[0][0] = ans.m[1][1] = 1;
ans.m[0][1] = ans.m[1][0] = 0;
while (n) {
if (n & 1) ans = multi(ans, a);
a = multi(a, a);
n >>= 1;
}
return ans.m[0][1];
}
int main() {
int n;
while (cin>>n&&n!=-1) {
cout << matrix_pow(base, n) << endl;
}
return 0;
}