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