矩陣的快速冪及應用

來源:互聯網
上載者:User

以二階矩陣為例。典型的斐波那契數列,就可以使用矩陣相乘來求解。

如果不考慮乘法的話,複雜度應該是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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.