【问题标题】:Implement modInverse using Extended Euclid Algorithm in Java在 Java 中使用扩展欧几里得算法实现 modInverse
【发布时间】:2021-05-22 16:34:35
【问题描述】:

不应使用 BigInteger 类的 modInverse 方法。我尝试并使用了这种方法,但它没有产生正确的结果。任何帮助将不胜感激。

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

【问题讨论】:

    标签: java algorithm euclidean-algorithm


    【解决方案1】:

    在else-branch中,第一个返回值应该是output[1]而不是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]
            };
        }
    }
    

    您可以在这里测试实现:https://onlinegdb.com/volwDTwnl

    【讨论】:

    • 由于 OP 似乎想要实现 modInverse ,因此值得一提的是,如果 output[2] 给出的 gcd 为 1 那么 output[0]a 模数 b 的倒数,否则不存在这样的逆,即a,b不是互质的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-26
    相关资源
    最近更新 更多