Fast power and Matrix fast power

Source: Internet
Author: User

The idea of a fast power:

is still the algorithm related to the 2-point method: (Many O (LOGN) algorithms are two-way ah ... )

But the fast power has a previous problem, that is, the data type must meet the binding law

for the general solution: a^8 = A * A * a * a * a * a * a * a * a total of 7 multiplication operations, the average decomposition: a^82 so we just need 4 times multiplication; we can also decompose it: A^6222 This reduces the number of multiplication operations to 3 times. 
 int  Qpow (int  A, int   b) { if  (b = = 0 ) return  1  ;  int  x = 1      while   (n) { if  (N&1 ) x *= A;        A  *= A;    n  >>= 1  ;  return   x;}  
The idea of a matrix fast power:

Define a matrix class that overloads the operator to satisfy the binding law:

  

classmatrix{ Public:    intN; int**m; Matrix (intn =2) {m=New int*[n];  for(inti =0; I < n; i++) {M[i]=New int[n]; } N=N;    Clear (); }    voidClear () {///empties the matrix to a 0 matrix         for(inti =0; i < N; i++) {memset (m[i],0,sizeof(int) *N); }    }    voidUnit () {///To set a matrix as a cell matrixClear ();  for(inti =0; i < N; i++) {M[i][i]=1; }} Matrixoperator= (Matrix &se) {////Assignment Matrix (SE.        N);  for(inti =0; I < SE. N i++){             for(intj =0; J < SE. N J + +) {M[i][j]=Se.m[i][j]; }        }        return* This; } Matrixoperator* (Matrix &se) {///matrix multiplication; matrix rslt (SE.        N);  for(inti =0; I < SE. N i++){             for(intj =0; J < SE. N J + +){                 for(intK =0; K < SE. N k++) {Rslt.m[i][j]+ = m[i][k] *Se.m[k][j]; }            }        }        returnrslt; }};
int N) {    Matrix rslt (A.N);    Rslt.unit ();     if 0 return rslt;      while (n) {        if(n&1) rslt *= A;        A*=A;        n>>=1;    }     return rslt;}

    

Fast power and Matrix fast power

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.