integer n-th square
Suppose an integer is 10, and how to solve the 10 of the 75-way quickest.
1.75 binary number in the form of 1001011
2.10 of 75 Square =10^64x10^8x10^2x10^1
In this process, we first find out the 10^1, and then according to the 10^2, and then according to 10^2 to find out 10^4, ..., finally, according to 10^32 to find out 10^64, that is, 75 of the binary number form a total number of bits, we will be on the original basis of the square several times. During step 2, the result is multiplied by the current square number only if it encounters a bit of 1 o'clock. For example, 10^64, 10^8, 10^2, 10^1 should be tired.
/**
* *
/static int ex2 (int n, int m) {
int pingfangshu = n;//n 1-square
int result = 1;
while (M! = 0) {
//encounters 1 multiplicative now power
if ((M & 1)! = 0)
result *= Pingfangshu;
Once per shift, power
Pingfangshu = Pingfangshu * Pingfangshu;
Move right One
m >>= 1;
}
return result;
}
matrix multiplication
/**
* matrix multiplication
* Matrix 1 is n*m matrix, Matrix 2 is m*p matrix
* result is n*p Matrix */public
static long[][] Matrixmultiply (long[][] M1, long[][] m2) {
final int n = m1.length;
Final int m = m1[0].length;
Final int p = m2[0].length;
Long[][] result = new long[n][p];//the number of rows with the number of lines of M1, columns of m2 columns for
(int i = 0; i < n; i++) {for
(int j = 0; J < ; P J + +) {for
(int k = 0; k < m; k++) {
Result[i][j] + = m1[i][k] * m2[k][j];
}}
}
return result;
}
the n-th square of the matrix
To find the N-square of the Matrix, the idea and the N-squared approximation of integers, the difference is that matrix multiplication and integer multiplication are not the same in detail, but for how to multiply faster, the principle is consistent.
/** * Find matrix the P-sub-square * @param matrix * @param p * @return */public static long [] Matrixpower (long[][] matrix, int p) {//Initialize result as unit matrix, diagonal 1 long[][] result = new Long[matrix.length][matrix[0].
Length];
The unit matrix, equivalent to an integer of 1 for (int i = 0; i < result.length; i++) {result[i][i] = 1; }//square number long[][] Pingfang = Matrix; One-party for (; p! = 0; p >>= 1) {if ((P & 1)! = 0) {//current bits the lowest bit is 1, multiply the current squared number into the result = Matri
Xmultiply (result, Pingfang);
}//squared number continues to turn Pingfang = matrixmultiply (Pingfang, Pingfang);
} return result; }