非递归快速幂
a
1
5
(
10
)
=
a
111
1
(
2
)
=
a
100
0
(
2
)
∗
a
10
0
(
2
)
∗
a
1
0
(
2
)
∗
a
1
(
2
)
a^{15_{(10)}}=a^{1111_{(2)}}=a^{1000_{(2)}}*a^{100_{(2)}}*a^{10_{(2)}}*a^{1_{(2)}}
a15(10)=a1111(2)=a1000(2)∗a100(2)∗a10(2)∗a1(2)并且
a
100
0
(
2
)
=
a
10
0
(
2
)
∗
a
10
0
(
2
)
a^{1000_{(2)}}=a^{100_{(2)}}*a^{100_{(2)}}
a1000(2)=a100(2)∗a100(2)
publicstaticintfastPower2(int a,int b){int ans = a;int result =1;while(b >0){if((b&1)==1){
result = result*ans;}
ans = ans*ans;
b = b>>1;}return result;}
递归快速幂模除
(
a
∗
b
)
%
c
=
(
(
a
%
c
)
∗
(
b
%
c
)
)
%
c
(a*b)\%c=((a\%c)*(b\%c))\%c
(a∗b)%c=((a%c)∗(b%c))%c
publicstaticintfastPowerMod2(int a,int b,int mod){int ans = a;int result =1;while(b >0){if((b&1)==1){
result =(int)(((long)(result*ans))%mod);}
ans =(int)((long)(ans*ans))%mod;
b = b>>1;}return result;}
矩阵快速幂
publicstaticint[][]fastMatrixPowerMod(int[][] a,int b,int mod){int[][] result ={{1,0},{0,1}};int[][] ans = a;while(b >0){if((b&1)>0)
result =matrixPowerMod(result,ans,mod);
ans =matrixPowerMod(ans, ans, mod);
b = b>>1;}return result;}publicstaticint[][]matrixPowerMod(int[][] a,int[][] b,int mod){int rows, columns;
rows = a.length; columns=a[0].length;int[][] c =newint[rows][columns];for(int i =0; i < rows; i++)for(int j =0; j < columns; j++)for(int k =0; k < columns; k++)
c[i][j]=(int)(((long)c[i][j]+(long)a[i][k]*b[k][j])%mod);return c;