以二阶矩阵为例。典型的斐波那契数列,就可以使用矩阵相乘来求解。
如果不考虑乘法的话,复杂度应该是lgn.
下面只给出计算矩阵快速幂的方法
#include <iostream> #define L 10000 using 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; }