码迷,mamicode.com
首页 > 其他好文 > 详细

二进制快速幂及矩阵快速幂

时间:2018-04-04 23:13:52      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:快速   pow   str   i++   int   div   one   alt   return   

二进制快速幂

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

二进制快速幂很好理解:

假设我们要求a^b,那么其实b是可以拆成二进制的,该二进制数第i位的权为2^(i-1),例如当b==11时,11的二进制是1011,11 = 23×1 + 22×0 + 21×1 + 2o×1,因此,我们将a11转化为算 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

 

 

 

二进制快速幂及矩阵快速幂

标签:快速   pow   str   i++   int   div   one   alt   return   

原文地址:https://www.cnblogs.com/ganster/p/8719284.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!