The operation of exponentiation is generally a multiplication of b times, for example, 2^4 = 2 *2 *2 * 2. For decimals, we can accumulate and multiply in this way. For larger times, there is a simpler method.
For example:
5 ^ 11 = 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5 * 5
The binary number of 11 is 1011, which is 2 to the power of zero, 1, 2 to the power of 1, 2, and 2 to the power of 3, 8.
Exactly 5 ^ 11 = 5 ^ 1 * 5 ^ 2 * 5 ^ 8
It used to be multiplied by 11 times, but now it only needs to be multiplied by 4 times.
This is the process of fast power deduction.
Source code:
public class Qmi {
public static int qmi(int a,int b) {
int res = 1;
while(b!=0) {
循环右移直到数为0
if((b&1)==1) {
对次数进行位运算判断最后一位是否为1
res = res*a; 累乘
}
a=a*a; a ^ 1, a ^ 2, a ^ 4, a ^ 8 .....
b=b>>1; 循环右移
}
return res;
}