C++ x的y次方对n取模

模运算满足分配率,对于任意的整数 a,b,q,r,n,可以构造:
a = K1 * n + q
b = K2 * n + r
(a*b) mod n = ((a mod n) * (b mod n)) mod n = q * r

int pow(int x, int y, int mod) {  
    int res = 1;  
    while(y)  
    {  
        if(y & 1) {
            res =  (res * x) % mod; 
        }
        x = (x * x) % mod;  
        y = y / 2;  
    }  
    return res;  
}  

参考:
https://www.zhihu.com/question/41361614/answer/337105745
https://blog.csdn.net/sqx2011/article/details/8241713

你可能感兴趣的:(C/C++)