zoukankan      html  css  js  c++  java
  • 二进制快速幂及矩阵快速幂

    二进制快速幂

    二进制快速幂虽然不难写,但是无奈总是会忘,所以还是在这里把板子写一下。

    二进制快速幂很好理解:

    假设我们要求a^b,那么其实b是可以拆成二进制的,该二进制数第i位的权为2^(i-1),例如当b==11时,11的二进制是1011,11 = 2³×1 + 2²×0 + 2¹×1 + 2º×1,因此,我们将a¹¹转化为算 a2^0*a2^1*a2^3

    int poww(int a, int b) {
        int ans = 1, base = a;
        while (b != 0) {
            if (b & 1 != 0)
                ans *= base;
                base *= base;
                b >>= 1;
        }
        return ans;
    }
    View Code

    矩阵快速幂

    类似于二进制快速幂,只不过将数相乘变成了矩阵相乘而已

     

    struct Matrix {
      int mat[N][N];
      int x, y;
      Matrix() {
          for (int i = 1; i <= N - 1; i++) mat[i][i] = 1;
      }
    };
    
    void mat_mul(Matrix a, Matrix b, Matrix &c) {
      Matrix c;
      memset(c.mat, 0, sizeof(c.mat));
      c.x = a.x;
      c.y = b.y;
      for (int i = 1; i <= c.x; i++)
        for (int j = 1; j <= c.y; j++)
          for (int k = 1; k <= a.y; k++)
            c.mat[i][j] += a.mat[i][k] * b.mat[k][j];
      return;
    }
    
    void mat_pow(Matrix &a, int b) {
      Matrix ans, base = a;
      ans.x = a.x;
      ans.y = a.y;
      while (b != 0) {
          if (b & 1) mat_mul(ans, base, ans);
          mat_mul(base, base, base);
          b >>= 1;
      }
    }
    View Code

     

     

  • 相关阅读:
    HBase 负载均衡
    HBase的写事务,MVCC及新的写线程模型
    HBase RegionServer宕机处理恢复
    分布式事务实现-Percolator
    MVC框架
    06-JS中li移动第二种形式
    05-JS中li移动第一种形式
    04-JS中文档碎片
    03-JS中添加节点
    02-JS中父节点
  • 原文地址:https://www.cnblogs.com/ganster/p/8719284.html
Copyright © 2011-2022 走看看