簡體   English   中英

Java中的模冪運算(算法給出錯誤的答案)

[英]Modular Exponentiation in java (the algorithm gives a wrong answer)

我正在嘗試實現模塊化冪運算,但我無法獲得正確的答案:

公共靜態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

對於零的指數位,您什么也不做。 對於2 0的指數和2 2048的指數,您不會得到相同的結果嗎?

這些語句應從if子句中得出,並在循環的每次迭代中執行,無論該位是零還是1:

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

同樣,使用e.testBit(i)遍歷指數的位將更有效且更容易理解。 即使不允許使用modPow()testBit()應該可以。


這是我的版本,包括該錯誤的修復程序以及我刪除字符串轉換的建議。 對於一般數字,它似乎也可以可靠地工作。 它不處理負指數和其他一些特殊情況。

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;
  }

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM