微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在 Java 中使用扩展 Euclid 算法实现 modInverse

如何解决在 Java 中使用扩展 Euclid 算法实现 modInverse

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

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

解决方法

在 else 分支中,第一个返回值应该是 output[1] 而不是 output[0]

public static int[] extendedgcd(int a,int b) {
    if (b == 0) {
        return new int[]{1,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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。