快速幂用于快速求解a的b次方问题。 时间复杂度为(logn)
例如:求解4的5次方
5的二进制数为101
4
5
4^5
45=
4
(
2
2
+
2
0
)
4^{(2^2+2^0)}
4(22+20)=
4
2
2
∗
4
2
0
4^{2^2}*4^{2^0}
422∗420=
4
2
1
+
2
1
∗
4
2
0
4^{2^1+2^1}*4^{2^0}
421+21∗420=
4
2
0
+
2
0
+
2
0
+
2
0
∗
4
2
0
4^{2^0+2^0+2^0+2^0}*4^{2^0}
420+20+20+20∗420
上式中,因为b的二进制为101,最低位的1,即为乘一次b,最高的1,即为乘
2
2
2^2
22次b(b的平方后的平方),遇到0时不乘。
- ①令结果res=1,以ans= 4 2 0 4^{2^0} 420=a
- ②将b用二进制表示,与1做&运算,判断最低位是否为1
- ③如果b的最低位为1,则用结果res乘上ans
- ④每次循环后,ans都要变成平方(因为二进制高一位就是原来的平方)
- ⑤b二进制右移一次,重复②~④
import java.util.Scanner;
public class quickPow {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
int a=scanner.nextInt();
int b=scanner.nextInt();
long res=quickpow(a, b);
System.out.println(res);
}
public static long quickpow(int a,int b) {
long ans=a;
long res=1;
while(b!=0) {
if((b&1)!=0) {
res*=ans;
}
ans*=ans;
b>>=1;
}
return res;
}
}