Ways to do modulo multiplication with primitive types

后端 未结 7 2131
野趣味
野趣味 2020-12-05 08:13

Is there a way to build e.g. (853467 * 21660421200929) % 100000000000007 without BigInteger libraries (note that each number fits into a 64 bit integer but the

7条回答
  •  日久生厌
    2020-12-05 08:42

    You should use Russian Peasant multiplication. It uses repeated doubling to compute all the values (b*2^i)%m, and adds them in if the ith bit of a is set.

    uint64_t mulmod(uint64_t a, uint64_t b, uint64_t m) {
        int64_t res = 0;
        while (a != 0) {
            if (a & 1) res = (res + b) % m;
            a >>= 1;
            b = (b << 1) % m;
        }
        return res;
    }
    

    It improves upon your algorithm because it takes O(log(a)) time, not O(a) time.

    Caveats: unsigned, and works only if m is 63 bits or less.

提交回复
热议问题