## Fast power / fast power matrix

Fast power can effectively reduce the amount of calculation by simplifying equation;

8 5 ^ e.g., without in any way simplification, it is 8 * 8 * 8 * 8 * 8;

Fast power index idea is to decompose, thereby reducing the number of calculations, the reference index is a secondary system on separation;

For 5, can be made into two strings 101, so 5 + 0 = 2 ^ 2 ^ 2;

Therefore, 8 ^ 1 ^ 5 = 8 * 8 ^ 4, thereby effectively calculated from twice to five times of the calculation;

```int quickpow ( int A, int b) {
int RES = . 1 ; // for storing results;
int ANS = A; // used to store a binary b-th power;
the while (! b = 0 ) {
IF (b% 2 == . 1 )
RES * = ANS;
ANS * = ANS;
B / = 2 ;
}
return RES;
}```

It is worth noting that a ans * = ans, since each cycle of the original square is a ^ 2, it is equivalent to a ^ 2 * a ^ 2;

Matrices same thinking power and fast, and it is thought the use of decomposition, the decomposition product of the matrix, is that multiplication is matrix multiplication be substituted;

```vector<vector<int>> multi(vector<vector<int>>m1, vector<vector<int>>m2) {
vector<vector<int>> m3;
m3.resize(n);
for (int i = 0; i < n; i++) {
m3[i].resize(n);
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
for (int k = 0; k < n; k++) {
m3[i][j] += m1[i][k] * m2[k][j];
}
}
}
return m3;
}

vector<vector<int>> quckmatrix(vector<vector<int>> m) {
vector<vector<int>> ans=m;
vector<vector<int>> res;
res.resize(n);
for (int i = 0; i < n; i++) {
RES [I] .resize (n-);
}
for (int I = 0; I <n-; I ++) {
// matrix
RES [I] [I] =. 1;
}
the while (k> 0) {
// for k binary operation;
IF (K == 2%. 1) {
RES = Multi (RES, ANS);
}
K / = 2;
ANS = Multi (ANS, ANS);
}
return RES;
}
```

### Guess you like

Origin www.cnblogs.com/songlinxuan/p/12432042.html
Recommended
Ranking
Daily