java - 模逆和 BigInteger 除法

标签 java algorithm

我一直在研究计算大整数的模逆的问题,即 a^-1 mod n。并且一直在使用 BigInteger 的内置函数 modInverse 来检查我的工作。

我已经按照 Menezes 等人的应用密码学手册中所示对算法进行了编码。不幸的是,我没有得到所有整数的正确结果。

我的想法是 q = a.divide(b) 行是我的问题,因为除法函数没有很好的文档记录(IMO)(我的代码也有类似的问题)。 BigInteger.divide(val) 是舍入还是截断?我的假设是截断,因为文档说它模仿了 int 的行为。感谢任何其他见解。

这是我一直在使用的代码:

private static BigInteger modInverse(BigInteger a, BigInteger b) throws ArithmeticException {
    //trivial case: b = 0 => a^-1 = 1
    if (b.equals(BigInteger.ZERO)) {
        return BigInteger.ONE;
    }
    //all other cases
    BigInteger x2 = BigInteger.ONE;
    BigInteger x1 = BigInteger.ZERO;
    BigInteger y2 = BigInteger.ZERO;
    BigInteger y1 = BigInteger.ONE;
    BigInteger x, y, q, r;
    while (b.compareTo(BigInteger.ZERO) == 1) {
        q = a.divide(b);
        r = a.subtract(q.multiply(b));
        x = x2.subtract(q.multiply(x1));
        y = y2.subtract(q.multiply(y1));
        a = b;
        b = r;
        x2 = x1;
        x1 = x;
        y2 = y1;
        y1 = y;
    }
    if (!a.equals(BigInteger.ONE))
        throw new ArithmeticException("a and n are not coprime");
    return x2;
}

产生错误输入的输入示例是:
一个:123456789
b: 2^809 - 1

产生预期结果的输入示例是:
一个:123456789
b: 2^807 - 1

最佳答案

以下是 Java 语言规范中整数除法的规定:

JLS 15.17.2 Division Operator

Integer division rounds toward 0. That is, the quotient produced for operands n and d that are integers after binary numeric promotion is an integer value q whose magnitude is as large as possible while satisfying |d·q|<=|n|; moreover, q is positive when |n|>=|d| and n and d have the same sign, but q is negative when |n|>=|d| and n and d have opposite signs.

关于java - 模逆和 BigInteger 除法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2941291/

相关文章:

java - 如何在 Java 中创建多堆栈

Java 泛型 : Instantiating arrays with parameterized types: illegal?

algorithm - shell排序什么时候进行冗余比较?

c - 为什么 spoj 对此 "Even Count"的解决方案给出了错误的答案

java - Jackson 通用类型引用 + enableDefaultTyping 问题

java - 如何从 URL 获取最终 URL(浏览器最后将加载的 URL)?

java - 如何在 Play Framework 模板中使用我自己的 Iterable

algorithm - 以 O(1) 访问任意元素的随机递增序列?

c++ - 合并排序无法在流程结束时合并零件

algorithm - 检查数字 N 是否是 3 和 5 的倍数之和,因为 N 可能大到 100,000