【问题标题】:Modular reduction of big numbers大数的模块化减少
【发布时间】:2015-09-18 10:27:54
【问题描述】:

对于一个玩具程序,我需要一种有效的计算方法

(2**64 * x) % m

其中xm 是java longs 和** 表示求幂。这可以计算为

 BigInteger.valueOf(x).shiftLeft(64).mod(BigInteger.valueOf(m)).longValue()

或通过反复将x 向左移动并减少,但两者都很慢。这不是过早的优化。

说明

‣ 任何使用BigInteger 的算法都可能比上面的表达式慢。

‣ 你可以假设m 对于int 来说太大了,否则

 long n = (1L<<32) % m; 
 return ((n*n) % m) * (x % m)) % m

会的。

‣ 慢移和归约算法类似于

// assuming x >= 0
long shift32Left(long x, long m) {
    long result = x % m;
    for (int i=0; i<64; ++i) {
        x <<= 1;
        // here, `x<0` handles overflow
        if (x<0 || x>=m) {
            x -= m;
        }
    }
}

【问题讨论】:

  • 你的意思是:(2^64 * x) % m ?
  • 关于m 和/或x 的任何限制/信息?
  • @hqt 是的,假设您不是指xor。我的意思是 \$x^{64}\$ 但 tex 表示法不适用于 SO。
  • @Sirko 不,除了它们很大。适合int 的情况很容易,可以单独处理。

标签: java long-integer arithmetic-expressions


【解决方案1】:

一般形式: (a1 * a2 * a3 ... * an) % m = [(a1 % m) * (a2 % m) * ... * (a3 % m) ] % m

应用上面的公式,我们有:

(2^64 * x) % m = (((2^64) % m) * (x % m)) % m

第一部分:2^64 mod m。我可以提出更一般的情况:2^t mod m。我有这个伪代码。将在N(log t) 次中运行。这个仅用于 t 和 m 的伪代码是普通整数。根据 t 和 m 的范围,您可以修复内部函数计算以在合适的点使用 BigInteger。

long solve(long t, long m) {
   if (t == 0) return 1 % m;
   if (t == 1) return t % m;
   long res = solve(t/2, m);
   res = (res * res) % m;
   if (t % 2 == 1) res = (res * 2) % m;
   return res;
}

感谢 OldCurmudgeon。上面的代码可以是简单的一行:

BigInteger res = (new BigInteger("2")).
   modPow(new BigInteger("64"), new BigInteger("" + m));

这里是modPow的实现。此实现使用不同的方法。算法从 m 开始:将 m 分解为 m = 2^k*q。然后会找到 2^k 和 q 的模然后使用 Chinese Reminder theorem 组合结果。

 public BigInteger modPow(BigInteger exponent, BigInteger m) {
        if (m.signum <= 0)
            throw new ArithmeticException("BigInteger: modulus not positive");

        // Trivial cases
        if (exponent.signum == 0)
            return (m.equals(ONE) ? ZERO : ONE);

        if (this.equals(ONE))
            return (m.equals(ONE) ? ZERO : ONE);

        if (this.equals(ZERO) && exponent.signum >= 0)
            return ZERO;

        if (this.equals(negConst[1]) && (!exponent.testBit(0)))
            return (m.equals(ONE) ? ZERO : ONE);

        boolean invertResult;
        if ((invertResult = (exponent.signum < 0)))
            exponent = exponent.negate();

        BigInteger base = (this.signum < 0 || this.compareTo(m) >= 0
                           ? this.mod(m) : this);
        BigInteger result;
        if (m.testBit(0)) { // odd modulus
            result = base.oddModPow(exponent, m);
        } else {
            /*
             * Even modulus.  Tear it into an "odd part" (m1) and power of two
             * (m2), exponentiate mod m1, manually exponentiate mod m2, and
             * use Chinese Remainder Theorem to combine results.
             */

            // Tear m apart into odd part (m1) and power of 2 (m2)
            int p = m.getLowestSetBit();   // Max pow of 2 that divides m

            BigInteger m1 = m.shiftRight(p);  // m/2**p
            BigInteger m2 = ONE.shiftLeft(p); // 2**p

            // Calculate new base from m1
            BigInteger base2 = (this.signum < 0 || this.compareTo(m1) >= 0
                                ? this.mod(m1) : this);

            // Caculate (base ** exponent) mod m1.
            BigInteger a1 = (m1.equals(ONE) ? ZERO :
                             base2.oddModPow(exponent, m1));

            // Calculate (this ** exponent) mod m2
            BigInteger a2 = base.modPow2(exponent, p);

            // Combine results using Chinese Remainder Theorem
            BigInteger y1 = m2.modInverse(m1);
            BigInteger y2 = m1.modInverse(m2);

            if (m.mag.length < MAX_MAG_LENGTH / 2) {
                result = a1.multiply(m2).multiply(y1).add(a2.multiply(m1).multiply(y2)).mod(m);
            } else {
                MutableBigInteger t1 = new MutableBigInteger();
                new MutableBigInteger(a1.multiply(m2)).multiply(new MutableBigInteger(y1), t1);
                MutableBigInteger t2 = new MutableBigInteger();
                new MutableBigInteger(a2.multiply(m1)).multiply(new MutableBigInteger(y2), t2);
                t1.add(t2);
                MutableBigInteger q = new MutableBigInteger();
                result = t1.divide(new MutableBigInteger(m), q).toBigInteger();
            }
        }

        return (invertResult ? result.modInverse(m) : result);
    }

对于第二部分:您可以轻松使用BigInteger 或简单的正常计算,取决于 x 和 m 的范围。

【讨论】:

  • BigIntegermodPow 可以处理2^64%m
  • @OldCurmudgeon 我编辑了我的答案。似乎 modPow 实现更快,因为 java 实现包括我的算法(break exponent/2)并进行了一些修改......
  • @hqt 恐怕你错过了我的BigInteger 方法(这比我需要的要慢)。
猜你喜欢
  • 1970-01-01
  • 2019-02-28
  • 1970-01-01
  • 2020-11-15
  • 2017-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多