【快速幂】快速幂qmi(a, b, p)的应用:快速幂的精髓在于对于b次方,把b拆成x0 * 2^0 + x1 * 2^1 + x2 ^ 2... 这样的形式,也就是把b换成他的二进制,如果某一位为1,那么就把答案*a,接下来下一位的1是上一位的^2了,所以需要把a变成a*a。
举个🌰吧:例如求3^10,那么a = 3,b = 10,res = 1
先把10换成二进制的1010
1.最后一位是0,res不变,a = a * a = 9
2.倒数第二位是1,res = res * a = 1 * 9 = 9,a = a * a = 81
3.倒数第三位是0,res不变,a = a * a = 81 * 81
4.倒数第四位是1,res = res * a = 9 * 81 * 81 = 59049
class Solution {
double qmi(double a, int b) {
double res = 1;
while (b != 0) {
if ((b & 1) == 1) res = res * a;
b >>>= 1;
a *= a;
}
return res;
}
public double myPow(double x, int n) {
return n < 0? 1.0 / qmi(x, -n): qmi(x, n);
}
}
class Solution {
public:
// 30:32
double qmi(double a, long b) {
double res = 1;
while (b) {
if (b & 1) res = res * a;
b >>= 1;
a *= a;
}
return res;
}
double myPow(double x, int n) {
long b = (long)n;
return b < 0? 1.0 / qmi(x, -b) :qmi(x, b);
}
};