BigInteger的问题

use*_*804 -1 java algorithm biginteger modulo bluej

您好我正在研究gcd和逆模运算的算法.

我必须使用BigInteger类,但我有一些问题.

那你能帮我吗?

问题是java programm不想用新的输入覆盖旧的BigInteger输入.

    import java.math.BigInteger;
    public class Gcd
 { 
public static void gcd(BigInteger a, BigInteger b){
    BigInteger  modulo =  b;
    BigInteger  wert = a;
    BigInteger  zwischenwert1 =  BigInteger.valueOf(1);
    BigInteger  zwischenwert2 = BigInteger.valueOf(0);

    BigInteger  zwischenwert3 = BigInteger.valueOf(0);
    BigInteger  zwischenwert4 = BigInteger.valueOf(1);
    BigInteger negativ = BigInteger.valueOf(-1);
    BigInteger  q;
    do{
        q = modulo.divide(wert);

        wert = modulo.subtract(wert.multiply(q));           
        zwischenwert3 = zwischenwert1.subtract(zwischenwert3.multiply(q));
        zwischenwert4 = zwischenwert2.subtract(zwischenwert4.multiply(q));

        modulo = negativ.multiply((wert.subtract(modulo)).divide(q));
        zwischenwert1 = negativ.multiply((zwischenwert3.subtract(zwischenwert1)).divide(q));
        zwischenwert2 = negativ.multiply((zwischenwert4.subtract(zwischenwert2)).divide(q));         

    }while((modulo.signum()>1)&&(wert.signum()>1));
      System.out.println("gcd("+a+","+b+") = "+zwischenwert3+" * "+b+ " + "+ zwischenwert4+" * "+ a+" = "+((BigInteger.valueOf(b).multiply(zwischenwert3)).add((BigInteger.valueOf(a).multiply(zwischenwert4)))));
    if (((BigInteger.valueOf(b).multiply(zwischenwert3)).add((BigInteger.valueOf(a).multiply(zwischenwert4)))).signum()==1)
        System.out.println("Inverse "+a+" mod "+b+" is"+zwischenwert4);
    else
        System.out.println("no Inverse!");

}}
Run Code Online (Sandbox Code Playgroud)

小智 5

您不必编写自己的gcd方法,因为它可以在BigInteger类中使用.

a.gcd(b)
Run Code Online (Sandbox Code Playgroud)