Ways to do modulo multiplication with primitive types

后端 未结 7 2133
野趣味
野趣味 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

    I can suggest an improvement for your algorithm.

    You actually calculate a * b iteratively by adding each time b, doing modulo after each iteration. It's better to add each time b * x, whereas x is determined so that b * x won't overflow.

    int64_t mulmod(int64_t a, int64_t b, int64_t m)
    {
        a %= m;
        b %= m;
    
        int64_t x = 1;
        int64_t bx = b;
    
        while (x < a)
        {
            int64_t bb = bx * 2;
            if (bb <= bx)
                break; // overflow
    
            x *= 2;
            bx = bb;
        }
    
        int64_t ans = 0;
    
        for (; x < a; a -= x)
            ans = (ans + bx) % m;
    
        return (ans + a*b) % m;
    }
    

提交回复
热议问题