1

modInverse method of class BigInteger should not be used. I tried and used this method but it does not produce the correct result. Any help would be appreciated.

public static int[] extendedgcd(int a, int b) {
        if (b==0) {
            return new int[]{1, 0, a};
        } else {
            int output[] = extendedgcd(b, a%b);
            return new int[]{output[0], output[0]-((a/b)*output[1]), output[2]};
        }
    }
swishy
  • 21
  • 1

1 Answers1

1

In the else-branch, the first return value should be output[1] instead of output[0]:

public static int[] extendedgcd(int a, int b) {
    if (b == 0) {
        return new int[]{1, 0, a};
    } else {
        int output[] = extendedgcd(b, a % b);
        return new int[]{
            output[1],
            output[0] - ((a / b) * output[1]),
            output[2]
        };
    }
}

You can test the implementation here: https://onlinegdb.com/volwDTwnl

Zecong Hu
  • 2,584
  • 18
  • 33
  • 1
    Since OP seems to want to implement `modInverse` , its worth mentioning that if the gcd given by `output[2]` is 1 then `output[0]` is the inverse of `a` modulus `b`, otherwise there doesn't exist such inverse i.e. a, b are not coprime. – SomeDude May 22 '21 at 18:41