Rapid power and Application of Matrices

Source: Internet
Author: User

Take the second-order matrix as an example. A typical Fibonacci series can be solved by multiplication of matrices.

If multiplication is not considered, the complexity should be lgn.

The following describes how to calculate the power of a matrix.

# Include <iostream> # define l 10000 using namespace STD; Class mymatrix {public: long a00, A01, A10, A11; mymatrix (); mymatrix (long _ a00, long long _ A01, long _ A10, 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 + signature * m2.a11, m1.a10 * m2.a00 + m1.a11 * m2.a10, m1.a10 * m2.a01 + m1.a11 * m2.a11);} // implement Recursive Sub-governance to solve const mymatrix pow_matrix (const mymatrix & M, long n) {If (n <= 1) return m; else {If (N & 1) {// odd mymatrix temp = pow_matrix (m, n/2); temp = temp * m; return temp ;} else {mymatrix temp = pow_matrix (m, n/2); temp = temp * temp; return temp ;}}// practically recursive optimization solution mymatrix ans2, 0, 1); // defines a unit array. The final result void pow_matrix_fast (const mymatrix & M, long n) {mymatrix temp = m; // temp. print_matrix (); While (n) {If (N & 1) {// odd number of ans2 = ans2 * temp;} temp = temp * temp; n >>= 1; // temp. print_matrix () ;}} mymatrix ans3 (,); void pow_matrix_fast2 (const mymatrix & M, long n) {mymatrix temp = m; // temp. print_matrix (); n --; while (n) {If (N & 1) {// odd 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 ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.