Ways to do modulo multiplication with primitive types

后端 未结 7 2134
野趣味
野趣味 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:48

    You could try something that breaks the multiplication up into additions:

    // compute (a * b) % m:
    
    unsigned int multmod(unsigned int a, unsigned int b, unsigned int m)
    {
        unsigned int result = 0;
    
        a %= m;
        b %= m;
    
        while (b)
        {
            if (b % 2 != 0)
            {
                result = (result + a) % m;
            }
    
            a = (a * 2) % m;
            b /= 2;
        }
    
        return result;
    }
    

提交回复
热议问题