1. 程式人生 > >二進制快速冪及矩陣快速冪

二進制快速冪及矩陣快速冪

opened pla class () sed ont base 矩陣 spl

二進制快速冪

二進制快速冪雖然不難寫,但是無奈總是會忘,所以還是在這裏把板子寫一下。

二進制快速冪很好理解:

假設我們要求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

二進制快速冪及矩陣快速冪