以二階矩陣為例。典型的斐波那契數列,就可以使用矩陣相乘來求解。
如果不考慮乘法的話,複雜度應該是lgn.
下面只給出計算矩陣快速冪的方法
#include <iostream>#define L 10000using namespace std;class MyMatrix{public:long long a00,a01,a10,a11;MyMatrix();MyMatrix(long long _a00, long long _a01, long long _a10, long long _a11):a00(_a00), a01(_a01), a10(_a10), a11(_a11) { }void print_matrix();};void MyMatrix::print_matrix(){cout << a00 << " " << a01 << endl << a10 << " " << a11 << endl;}const MyMatrix operator * (const MyMatrix & m1, const MyMatrix & m2){return MyMatrix(m1.a00 * m2.a00 + m1.a01 * m2.a10,m1.a00 * m2.a01 + m1.a01 * m2.a11,m1.a10 * m2.a00 + m1.a11 * m2.a10,m1.a10 * m2.a01 + m1.a11 * m2.a11);}//用 遞迴實現分治求解const MyMatrix pow_matrix(const MyMatrix & m, long long n){if( n <= 1)return m;else{if( n & 1){ //奇數MyMatrix temp = pow_matrix(m, n/2);temp = temp * temp * m;return temp;}else{MyMatrix temp = pow_matrix(m, n/2);temp = temp * temp;return temp;}}}//不實用遞迴最佳化求解MyMatrix ans2(1,0,0,1); //定義一個單位陣,存數最終結果void pow_matrix_fast(const MyMatrix & m,long long n){MyMatrix temp = m;//temp.print_matrix();while(n){if(n & 1){ //奇數ans2 = ans2 * temp;}temp = temp * temp;n >>= 1;//temp.print_matrix();}}MyMatrix ans3(1,2,3,4);void pow_matrix_fast2(const MyMatrix & m,long long n){MyMatrix temp = m;//temp.print_matrix();n--;while(n){if(n & 1){ //奇數ans3 = ans3 * temp;}temp = temp * temp;n >>= 1;//temp.print_matrix();}}int main() {MyMatrix m(1, 2, 3 ,4);MyMatrix ans = pow_matrix(m,6);ans.print_matrix();pow_matrix_fast(m, 6);ans2.print_matrix();pow_matrix_fast2(m, 6);ans3.print_matrix();return 0;}