快速幂【倍增+二分】
快速幂就是快速算底数的n次幂。其时间复杂度为 O(logN), 与朴素的O(N)相比效率有了极大的提高。
例如
![](https://gss3.bdstatic.com/7Po3dSag_xI4khGkpoWK1HF6hhy/baike/s%3D103/sign=885b42e39c16fdfadc6cc2ee878d8cea/d0c8a786c9177f3e48bd45c571cf3bc79e3d5668.jpg)
11的二进制是1011
11 = 2³×1 + 2²×0 + 2¹×1 + 2º×1
因此,我们将a¹¹转化为算![](https://gss3.bdstatic.com/-Po3dSag_xI4khGkpoWK1HF6hhy/baike/s%3D95/sign=257afe75a8773912c0268964f919a226/e850352ac65c1038803a760ab3119313b17e89b6.jpg)
![](https://gss3.bdstatic.com/-Po3dSag_xI4khGkpoWK1HF6hhy/baike/s%3D95/sign=257afe75a8773912c0268964f919a226/e850352ac65c1038803a760ab3119313b17e89b6.jpg)
常规求幂:
int pow0(int a,int b){ int r=1; while(b--) r*=a; return r; }
倍增法快速求幂:
int pow1(int a,int b){ int r=1,base=a;//初始r等于2的零次方,base等于a的2的零次方 while(b){ if(b&1) r*=base; base*=base; b>>=1; } return r; }
二分法快速求幂:
LL f(int x,int n){ if(n==0) return 1; else if(n==1) return x; else{ LL sub_res=f(x,n/2); res = sub_res*sub_res; if(n%2==1) res*=x; } return res; }