java中的模块化指数(算法给出了错误的答案)

时间:2014-03-13 22:42:11

标签: java modular exponentiation

我正在尝试实施Modular Exponentiation,但我无法得到正确答案:

public static 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

1 个答案:

答案 0 :(得分:1)

对于零指数位,您不做任何事情。如果指数为2 0 且指数为2 2048 ,你会得到相同的结果吗?

这些语句应该来自if子句,并且在循环的每次迭代中执行,无论该位是0还是1:

power=power.multiply(power);
power=power.mod(m);

此外,使用e.testBit(i)迭代指数的位将更有效,更容易理解。即使不允许使用modPow()testBit()也应该没问题。


这是我的版本,包括修复bug和我建议摆脱字符串转换。对于一般数字,它似乎也可靠地工作。它不处理负指数和其他一些特殊情况。

public class CrazyModPow
{

  public static void main(String[] argv)
  {
    for (int count = 1; true; ++count) {
      Random rnd = new Random();
      BigInteger base = BigInteger.probablePrime(512, rnd);
      BigInteger exp = BigInteger.probablePrime(512, rnd);
      BigInteger mod = BigInteger.probablePrime(1024, rnd);
      if (!base.modPow(exp, mod).equals(modPow(base, exp, mod))) {
        System.out.println("base: " + base);
        System.out.println("exp:  " + exp);
        System.out.println("mod:  " + mod);
      }
      else if ((count % 10) == 0) {
        System.out.printf("Tested %d times.%n", count);
      }
    }
  }

  public static BigInteger modPow(BigInteger base, BigInteger e, BigInteger m)
  {
    BigInteger result = BigInteger.ONE;
    base = base.mod(m);
    for (int idx = 0; idx < e.bitLength(); ++idx) {
      if (e.testBit(idx)) {
        result = result.multiply(base).mod(m);
      }
      base = base.multiply(base).mod(m);
    }
    return result;
  }

}