-1

Hello i am working on an algorithm for gcd and inverse modulo operations.

i have to use the BigInteger class but i have a few problems on this.

So could you help me please?

The problem is that by java programm doesnt want to overwrite the old BigInteger input with a new one.

    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!");

}}
MariuszS
  • 30,646
  • 12
  • 114
  • 155

2 Answers2

5

You don't have to write your own gcd method, as it is available in the BigInteger class.

a.gcd(b)
Marcin Krupa
  • 497
  • 2
  • 6
3

In java, all objects are passed by copy of reference, meaning if you pass a to your function and then change the value assigned to reference a, the original value will be unchanged, because you don't actually have access to the original reference, but a copy of it. You need to actually return a reference to the new object to let it escape the function.

For example:

public BigInteger mod(BigInteger a, BigInteger b){
  // .... create new value x
  return x;
}

By the way, as per the Wikipedia page, you can pretty much apply the following:

function gcd(a, b)
  while b ≠ 0
     t := b
     b := a mod b
     a := t
  return a
Giovanni Botta
  • 9,626
  • 5
  • 51
  • 94