以斐波那契数列为例,计算斐波那契数列的矩阵方法代码如下:
(快速幂、矩阵乘法)《挑战程序设计竞赛第二版》P199
#include#include using namespace std;typedef vector vec;typedef vector mat;int M = 10000;mat mul(mat &A,mat &B){ mat C(A.size(),vec(B[0].size())); for(int i = 0;i < A.size();i++) for(int k = 0;k < B.size();k++) for(int j = 0;j < B[0].size();j++) C[i][j] = (C[i][j] + A[i][k]*B[k][j])%M; return C;}mat pow(mat A,int n){ mat res(A.size(),vec(A.size())); for(int i = 0;i < A.size();i++) res[i][i] = 1; while(n > 0){ if(n & 1) res = mul(res,A); A = mul(A,A); n >>= 1; } return res;}void print(mat &A){ for(int i = 0;i < A.size();i++){ for(int j = 0;j < A[0].size();j++) cout << A[i][j] << " "; cout << endl; }} int main(){ mat A(2,vec(2)); A[0][0] = A[0][1] = A[1][0] = 1; A[1][1] = 0; print(A); A = pow(A,100); print(A); return 0;}