二进制快速幂
二进制快速幂虽然不难写,但是无奈总是会忘,所以还是在这里把板子写一下。
二进制快速幂很好理解:
假设我们要求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; }
矩阵快速幂
类似于二进制快速幂,只不过将数相乘变成了矩阵相乘而已
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; } }
原文地址:https://www.cnblogs.com/ganster/p/8719284.html
时间: 2024-10-14 17:12:10