【发布时间】:2014-03-13 22:42:11
【问题描述】:
我正在尝试实现模幂,但我无法得到正确的答案:
公共静态 BigInteger modPow(BigInteger b, BigInteger e, BigInteger m)
{ //计算模幂并返回BigInteger类的对象
BigInteger x= new BigInteger("1"); //The default value of x
BigInteger power ;
power=b.mod(m);
String t =e.toString(2); //convert the power to string of binary
String reverse = new StringBuffer(t).reverse().toString();
for (int i=0;i<reverse.length();i++ ) { //this loop to go over the string char by char by reverse
if(reverse.charAt(i)=='1') { //the start of if statement when the char is 1
x=x.multiply(power);
x=x.mod(m);
power=power.multiply(power);
power=power.mod(m);
} //the end of if statement
}//the end of for loop
return x;
} //the end of the method modPow
【问题讨论】:
标签: java modular exponentiation