具体理论参考相应算法书,
主要是应用了
(A*B)modC = ((AmodC)*B)modC
及对幂进行二进制分解来求的
上代码:
/**
* 从左到右
*/
public static long calc_1(long a, long b, long mod){
final String s = Long.toBinaryString(b);
int length = s.length();
long result = 1;
for(int i = 0; i < length; ++i){
char temp = s.charAt(i);
result = (result*result)%mod;
if(temp == '1'){
result = (result*a)%mod;
}
}
return result;
}
/**
* 从右到左
*/
public static long calc_2(long a, long b, long mod){
final String s = Long.toBinaryString(b);
int length = s.length() - 1;
long result = 1;
long p = a;
for(int i = length; i > -1; --i){
char temp = s.charAt(i);
if(temp == '1'){
result = (result*p)%mod;
}
p = (p*p)%mod;
}
return result;
}
public static void main(String[]args) throws Exception{
System.out.println(Test.calc_1(7, 560, 561));
System.out.println(Test.calc_2(7, 560, 561));
}