快速幂讲解
2015-07-12 23:34
441 查看
快速幂这个东西比较好理解,但实现起来到不老好办,记了几次老是忘,今天把它系统的总结一下防止忘记。
首先,快速幂的目的就是做到快速求幂,假设我们要求a^b,按照朴素算法就是把a连乘b次,这样一来时间复杂度是O(b)也即是O(n)级别,快速幂能做到O(logn),快了好多好多。它的原理如下:
假设我们要求a^b,那么其实b是可以拆成二进制的,该二进制数第i位的权为2^(i-1),例如当b==11时
a11=a(2^0+2^1+2^3) 11的二进制是1011,11 = 2³×1 + 2²×0 + 2¹×1 + 2º×1,因此,我们将a¹¹转化为算 a2^0*a2^1*a2^3,也就是a1*a2*a8 ,看出来快的多了吧原来算11次,现在算三次,但是这三项貌似不好求的样子....不急,下面会有详细解释。 由于是二进制,很自然地想到用位运算这个强大的工具:&和>> &运算通常用于二进制取位操作,例如一个数 & 1 的结果就是取二进制的最末位。还可以判断奇偶x&1==0为偶,x&1==1为奇。 >>运算比较单纯,二进制去掉最后一位,不多说了,先放代码再解释。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; }
代码很短,死记也可行,但最好还是理解一下吧,其实也很好理解,以b==11为例,b=>1011,二进制从右向左算,但乘出来的顺序是 a^(2^0)*a^(2^1)*a^(2^3),是从左向右的。我们不断的让base*=base目的即是累乘,以便随时对ans做出贡献。
其中要理解base*=base这一步:因为 base*base==base2,下一步再乘,就是base2*base2==base4,然后同理 base4*base4=base8,由此可以做到base-->base2-->base4-->base8-->base16-->base32.......指数正是 2^i ,再看上面的例子,a¹¹= a1*a2*a8,这三项就可以完美解决了,快速幂就是这样。
顺便啰嗦一句,由于指数函数是爆炸增长的函数,所以很有可能会爆掉int的范围,根据题意选择 long long还是mod某个数自己看着办。
矩阵快速幂也是这个道理,下面放一个求斐波那契数列的矩阵快速幂模板
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> using namespace std; const int mod = 10000; const int maxn = 35; int N; struct Matrix { int mat[maxn][maxn]; int x, y; Matrix() { memset(mat, 0, sizeof(mat)); for (int i = 1; i <= maxn - 5; i++) mat[i][i] = 1; } }; inline void mat_mul(Matrix a, Matrix b, 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]) % mod; c.mat[i][j] %= mod; } } } return ; } inline void mat_pow(Matrix &a, int z) { Matrix ans, base = a; ans.x = a.x; ans.y = a.y; while (z) { if (z & 1 == 1) mat_mul(ans, base, ans); mat_mul(base, base, base); z >>= 1; } a = ans; } int main() { while (cin >> N) { switch (N) { case -1: return 0; case 0: cout << "0" << endl; continue; case 1: cout << "1" << endl; continue; case 2: cout << "1" << endl; continue; } Matrix A, B; A.x = 2; A.y = 2; A.mat[1][1] = 1; A.mat[1][2] = 1; A.mat[2][1] = 1; A.mat[2][2] = 0; B.x = 2; B.y = 1; B.mat[1][1] = 1; B.mat[2][1] = 1; mat_pow(A, N - 1); mat_mul(A, B, B); cout << B.mat[1][1] << endl; } return 0; }
相关文章推荐
- ERROR 1044 (42000): Access denied for user ''@'localhost' to database 'mysql'
- 课程笔记 01:数据结构(清华) 绪论
- 虚函数
- linux下查看所有用户及所有用户组
- 搭建虚拟分区,便于隐藏自己的文件
- Linux软防火墙ACL匹配的优化点
- #Pragma Pack(n)与内存分配
- Tomcat和 Resin
- Linux软防火墙ACL匹配的优化点
- STM32 USART 波特率计算
- javac编译项目代码脚本片段
- 物联网,从百姓生活开始
- Spring3 MVC + jQuery easyUI 做的ajax版本用户管理
- RMI in Spring
- 鹊桥相会---编程马拉松
- NSURLConnection
- Maximum number of WAL files in the pg_xlog directory (1)
- Swift enumerate函数与??操作符
- enable_shared_from_this解析
- 滚动加载图片