矩阵快速幂
2015-11-05 09:37
197 查看
矩阵快速幂其实和常数的快速幂相似,复杂度log2(n)
比如说A^10, 10的二进制1010
也就是说A^10 = A^(2^0*0 + 2^1*1 + 2^2*0 + 2^3*1) 注意:荧光标记的字体刚好是利用了1010(2)从右往所数的每一个数字
算A^10的时候不用算10次,而是先算A^2, 然后算(A^2)^2;然后((A^2)^2)^2……这样就少算了很多次,
而A^10 = A^2 * ((A^2)^2)^2
上代码:
比如说A^10, 10的二进制1010
也就是说A^10 = A^(2^0*0 + 2^1*1 + 2^2*0 + 2^3*1) 注意:荧光标记的字体刚好是利用了1010(2)从右往所数的每一个数字
算A^10的时候不用算10次,而是先算A^2, 然后算(A^2)^2;然后((A^2)^2)^2……这样就少算了很多次,
而A^10 = A^2 * ((A^2)^2)^2
上代码:
#include <cstdio> #include <cstring> #include <iostream> #include <cstdlib> #define N 3 struct matrix { int arr ; }origin, res; matrix multiply(matrix x, matrix y) { matrix tmp; memset(tmp.arr, 0, sizeof(tmp.arr)); for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { for(int k = 0; k < N; k++) tmp.arr[i][j] += x.arr[i][k] * y.arr[k][j]; } } return tmp; } void init() { printf("随机数组如下:\n"); for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) { origin.arr[i][j] = rand() % 10; res.arr[i][j] = (i == j); printf("%8d", origin.arr[i][j]); } printf("\n"); } printf("\n"); } void cacl(int n) { printf("%d次幂的计算结果如下:\n", n); while(n) { if(n & 1) res = multiply(res, origin); origin = multiply(origin, origin); n >>= 1; } for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) printf("%8d", res.arr[i][j]); printf("\n"); } printf("\n"); } int main() { int n; while(~scanf("%d", &n)) { init(); cacl(n); } return 0; }
相关文章推荐
- 关于打包自定义标签,并导入项目使用时,出现java.lang.NoClassDefFoundError: JspException异常,解决方法和注意事项!
- DefaultHttpClient使用
- oracle 怎么debug
- Android利用反射获取状态栏(StatusBar)高度
- 打包Assetbundle并加载
- 疯狂的无人机:大疆面临小米和数百创业公司的集体“围剿”---ESM
- 【转】Android源代码查看途径
- 解决:Windows 强制升级为8.1之后 Mysql连接不上, VisualSVN Server无服务
- 【python】break和continue
- 动态绑定滚动条事件
- mysql 常用系统函数
- 携程Android App插件化和动态加载实践
- C++文件操作
- TCL智能电视ROOT教程 附ROOT工具下载
- myeclipse不能在线更新插件的解决办法
- 动态绑定滚动条事件
- JavaScript实现cookie的写入、读取、删除功能
- Visual Studio 如何创建解决方案
- VIJOS【1234】口袋的天空
- 开源浏览器引擎开发:Google 的人数是 Mozilla 的两倍