Calculate a*a mod n without overflow

后端 未结 5 1752

I need to calculate a*a mod n but a is fairly large, resulting in overflow when I square it. Doing ((a % n)*(a % n)) % n

5条回答
  •  臣服心动
    2020-12-02 01:13

    I know you no longer need this, and there is an alternative solution, but I want to add an alternative method to implement it. It provides two different techniques: the double and add algorithm, and the method to handle mod(a + b, n) with overflow detection.

    Double and add algorithm is usually used in fields where multiplication is not possible or too costly to calculate directly (such as elliptic curves), but we could adopt it to handle it in our situation to handle overflows instead.

    The following code is probably slower than the accepted solution (even when you optimize it), but if speed is not critical, you may prefer it for clarity.

    unsigned addmod(unsigned x, unsigned y, unsigned n)
    {
        // Precondition: x>= 1) {
            if (b & 1) {
                sum = addmod(sum, a, n);
            }
            a = addmod(a, a, n);
        }
        return sum;
    }
    

提交回复
热议问题