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

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.