The N-th power of an integer seeking (logN) time complexity of O and N-th power of a matrix

Integer power N

Assuming that an integer is 10, how to solve the 75 th fastest 10.
1.75 binary number is 1001011
75 power of 2.10 = 10 ^ 64 × 10 ^ 8 × 10 ^ 2 × 10 ^ 1

In this process, we first find the 10 ^ 1, 10 ^ 2 and then according then determined in accordance with 10 ^ 10 ^ 4 2, ......, and finally obtained 10 ^ 10 ^ 32 64 The, i.e., binary number 75 how many, we have the square several times based on the original total of.

  1. In the process of step 2, only 1 bit is encountered, it will result that multiplies the current number of square. For example, ^ 10 ^ 64,10 2,10 8,10 ^ ^ 1 should be multiplicative.
  /**
   * 巧算
   */
  static int ex2(int n, int m) {
    int pingFangShu = n; //n 的 1 次方
    int result = 1;
    while (m != 0) {
      //遇1累乘现在的幂
      if ((m & 1) != 0)
        result *= pingFangShu;
      //每移位一次,幂累乘方一次
      pingFangShu = pingFangShu * pingFangShu;
      //右移一位
      m >>= 1;
    }
    return result;
  }

Matrix Multiplication

  /**
   *   矩阵乘法
   *   矩阵1为n*m矩阵,矩阵2为m*p矩阵
   *   结果为n*p矩阵
   */
  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];// 新矩阵的行数为m1的行数,列数为m2的列数
    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;
  }

N-th power of a matrix

The Matrix N-th power, ideas and seeking integer N-th power close, the difference between matrix multiplication and integer multiplication is not the same as in the details, but for how quickly multiplied, the principle is the same.

  /**
   * 求矩阵matrix的p次方
   * @param matrix
   * @param p
   * @return
   */
  public static long[][] matrixPower(long[][] matrix, int p) {
    //初始化结果为单位矩阵,对角线为1
    long[][] result = new long[matrix.length][matrix[0].length];
    //单位矩阵,相当于整数的1
    for (int i = 0; i < result.length; i++) {
      result[i][i] = 1;
    }

    //平方数
    long[][] pingFang = matrix; // 一次方
    for (; p != 0; p >>= 1) {
      if ((p & 1) != 0) { // 当前二进制位最低位为1,将当前平方数乘到结果中
        result = matrixMultiply(result, pingFang);
      }
      //平方数继续上翻
      pingFang = matrixMultiply(pingFang, pingFang);
    }
    return result;
  }
Published 127 original articles · won 97 Like · views 310 000 +

Guess you like

Origin blog.csdn.net/zhengwei223/article/details/78758775