快速幂(全网最详细)

点击此处传送到全网最详细博客

代码1:

    public int fastPower(int x, int n) {
       int result = 1;
       while (n > 0 ){
           if(n % 2 == 0){
               //如果指数为偶数
               n = n / 2; //把指数缩小为一半
               x = x * x % 1000; //底数变大成原来的乘方
           }else {
               //如果结果为奇数
               n = n - 1;   //把指数减去1,使其变成一个偶数
               result = result * x % 1000; //此时记得要把指数为奇数时分离出来的底数的一次方收集好
               n = n / 2;   //此时指数为偶数,可以继续执行操作
               x = x * x % 1000;
           }
       }

       return result;
    }

优化1:压缩

    public int fastPower(int x, int n) {
       double result = 1;
       while (n > 0 ){
           if(n % 2 == 1){
               result = result * x % 1000; //此时记得要把指数为奇数时分离出来的底数的一次方收集好
           }
           n = n / 2;   //此时指数为偶数,可以继续执行操作
           x = x * x % 1000;
       }

优化2:位运算(目前更强)

    public int fastPower(int x, int n) {
       int result = 1;
       while (n > 0 ){
           if((n & 1) == 1){    //此处等价于if(power%2==1)
               result = result * x % 1000; //此时记得要把指数为奇数时分离出来的底数的一次方收集好
           }
           n = n >> 1;   //此处等价于power=power/2
           x = x * x % 1000;
       }

       return result;
    }

猜你喜欢

转载自blog.csdn.net/gjs935219/article/details/108661221