快速幂精讲+代码实现

普通求解幂的方法:

1 public int power(int a,int b){
2         int res = 1;
3         for (int i = 1; i <= b ; i++) {
4             res *= a;
5         }
6         return res;
7     }

是b个a累乘的结果,时间复杂度为O(n)。

 

而快速幂借助位权减小计算的时间复杂度,快速幂的事件复杂度为O(logn)。

快速幂的目的快速求幂,假设我们要求a^b,

假设我们要求a^b,把b转成二进制数,则该二进制数第i位的权为2^(i-1),例如当a == 2 ,b == 11时,b的二进制数为1011

    a11=a(2^0+2^1+2^3)
            211=2(2^0+2^1+2^3) =  2( 1*1 + 2*1 + 0*4 + 8*1 ) = 2 * 4 *1* 256
b的二进制从左到右的位权依次为1,2,4,8 , ... ,  2^(i-1),连续位置之间的位权组成一个等比数列;
而每个位置位权与基数所代表的值之间,如果每个位置上的值都为1的话,后一位是前一位的2次方(为什么是2次方呢?因为b被转换成了2进制数)。
下面给出快速幂的非递归写法:
 1     public int FastPower1(int a, int b) {
 2         //假设a和b是大于等于0的数,那么在幂运算中,结果的最小值为1
 3         int result = 1;
 4         //为了便于理解,这里多申请一个变量,位权
 5         int base_pow_pisotionPower = a;
 6         while (b != 0) {
 7             if ((b & 1) != 0) {
 8                 result *= base_pow_pisotionPower;
 9             }
10             b >>= 1;
11             base_pow_pisotionPower *= base_pow_pisotionPower;
12         }
13         return result;
14     }

 下面给出递归写法:

1 public int FastPower(int a,int b){
2         if (b==0) return 1;
3         if (b==1) return a;
4         int result = FastPower(a,b>>1);
5         result *= result;
6         if (b%2==1) result *= a;
7         return result;
8 }

 

posted on 2020-09-14 20:08  含光Aries  阅读(237)  评论(0编辑  收藏  举报