就是把一个高次的数转换成很多低次累乘的形式,类似进制转换的原理。
我们计算\(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; }