计算 a^b mod c
法1:直接求解
[cpp] view
plaincopy
-
int ans =1;
-
for i=1 to b
-
ans = ans * a;
-
ans = ans % c;
法2:a^b mod c = ( a mod c ) ^ b mod c
[cpp] view
plaincopy
-
int ans = 1;
-
a = a % c;
-
for i=1 to b
-
ans = ans * a;
-
ans = ans % c;
法3:由于某个因子取余后再相乘余数保持不变
a^b mod c = (a mod c)^b mod c
=(...(((a mod c)*a) mod c)*a) mod c)...*a)mod c
共有b个a相乘
[cpp] view
plaincopy
-
int ans = 1;
-
a = a % c;
-
for i=1 to b
-
ans = ans * a mod c;
-
ans = ans % c;
法4:当b 为
偶数时,a^b mod c = ( a^2 )^( b/2 ) mod c
= k^( b/2 ) mod c
当b为奇数时,a ^b mod c = ( ( a^2 )^( b/2 ) )* a mod c
= ( k^( b/2 )*a ) mod c
[html] view
plaincopy
-
int ans= 1;
-
int k = a*a;
-
if b mod 2 equal 1
-
ans = ( ans * a) mod c;
-
for i = 1 to b/2
-
ans = ( ans * k) mod c;
-
ans = ans mod c;
法5:对法4进行迭代,即:令 a = k;
b = b/2;
[cpp] view
plaincopy
-
int ans = 1, t = a;
-
while b > 0
-
if b mod 2 equal 1
-
ans = ( ans *t ) mod c;
-
b /= 2;
-
t = ( t *t ) mod c;
-
return ans;