快速幂,顾名思义就是快速求幂。
快速幂理解:https://www.cnblogs.com/CXCXCXC/p/4641812.html
eg: 求 2 100 2^{100} 2100
如果每次乘2,总共需要乘100次。
如果利用快速幂,每次计算 2 0 , 2 1 , 2 2 , 2 3 … 2^0,2^1,2^2,2^3 \dots 20,21,22,23… 可以将复杂度降低为 l o g n log n logn
private static int poww(int a,int b){
int result = 1;
while(b!=0){
if(b%2!=0) result *=a;
a*= a;
b>>=1;
System.out.println(b);
}
return result;
}
矩阵快速幂的板子:
https://vjudge.net/problem/POJ-3233
private static long[][] multiply(long[][] a, long[][] b,int n,int mod){
long[][] result = new long[80][80];
for(int i=1;i<=2*n;i++){
for(int j=1;j<=2*n;j++){
for(int k=1;k<=2*n;k++){
result[i][j] += ((a[i][k]*b[k][j])%mod);
result[i][j] %=mod;
}
}
}
return result;
}
private static long[][] quick(int k,int n,int mod){
long[][] cur = new long[80][80];
long[][] result = new long[80][80];
for(int i=1;i<=2*n;i++){
result[i][i]=1;
}
cur = matrix;
while(k!=0){
if(k%2 ==1) result = multiply(result, cur, n, mod);
cur = multiply(cur, cur, n, mod);
k/=2;
}
return result;
}