快速幂
2021/12/25 23:10:20
本文主要是介绍快速幂,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
快速幂
定义
就是把一个高次的数转换成很多低次累乘的形式,类似进制转换的原理。
优点
我们计算\(A^n\)的朴素的方法就是循环\(n\)次来求幂,这样便得到\(O(n)\)时间复杂度的方法,其实大家都想得到一种优化的方法即\(A^n=A^{\frac{n}{2}}*A^{\frac{n}{2}}\)。
一直递归下去,其间就可以省略很多不必要的计算,得到\(O(logn)\)的方法。
写法
#include<bits/stdc++.h> #define int long long using namespace std; //常规求幂 int pow1(int a, int b) { int r = 1; while (b--) { r *= a; } return r; } //一般 int pow2(int a, int b) { int r = 1, base = a; while (b != 0) { if (b % 2) { r *= base; } base *= base; b /= 2; } return r; } //位运算 int pow3(int x, int n) { if (n == 0) { return 1; } int t = 1; while (n != 0) { if(n & 1) { t *= x; } n >>= 1; x *= x; } return t; } //递归 int pow4(int m, int n) { if (n == 1) { return m; } int temp = pow4(m, n / 2); return (n % 2 == 0 ? 1 : m) * temp * temp; } signed main(unsigned) { int a, b; cin >> a >> b; cout << pow1(a, b) << endl; cout << pow2(a, b) << endl; cout << pow3(a, b) << endl; cout << pow4(a, b) << endl; return 0; }
这篇关于快速幂的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-06小米11i印度快充版ROM合集:极致体验,超越期待
- 2024-10-06【ROM下载】小米11i 5G 印度版系统, 疾速跃迁,定义新速度
- 2024-10-06【ROM下载】小米 11 青春活力版,青春无极限,活力全开
- 2024-10-05小米13T Pro系统合集:性能与摄影的极致融合,值得你升级的系统ROM
- 2024-10-01基于Python+Vue开发的医院门诊预约挂号系统
- 2024-10-01基于Python+Vue开发的旅游景区管理系统
- 2024-10-01RestfulAPI入门指南:打造简单易懂的API接口
- 2024-10-01初学者指南:了解和使用Server Action
- 2024-10-01Server Component入门指南:搭建与配置详解
- 2024-10-01React 中使用 useRequest 实现数据请求