描述:若b * x = 1 (mod p),则称b关于模p的乘法逆元为x。
条件:当b与p互质时,b关于模p的乘法逆元有唯一解;b与p不互质时,无解。
求法:由欧拉定理b^phi(p) = 1 (mod p)可知: x = b^(phi(p)-1) = b^(p-2)
1. 扩展欧几里得算法求逆元
1 LL extendEuclid(LL a, LL b, LL &x, LL &y) 2 { 3 if (0 == a && 0 == b) return -1; 4 if (0 == b) { 5 x = 1; 6 y = 0; 7 return a; 8 } 9 d = extendEuclid(b, a % b, y, x); 10 y -= a / b * x; 11 return d; 12 } 13 14 // bx = 1 (mod p) 15 LL modReverse(LL b, LL p) { 16 LL x, y; 17 LL d = extendEuclid(b, p, x, y); 18 if (d == 1) return (x % n + n) % n; 19 return -1; 20 }
2. bx = 1 (mod p)当b < p时的简洁求法
1 // bx = 1 (mod p) 2 // b < p 且b与p互质 3 LL modReverse(LL b, LL p) { 4 if (1 == b) return 1; 5 return modReverse(p % b, p) * (p - p / b) % p; 6 }
3. 利用欧拉函数x = b^(phi(p)-1) = b^(p-2)
1 // a^b mod p 2 LL fastModExp(LL a, LL b, LL p) { 3 LL tmp = a; 4 LL ret = 1L; 5 while(b) { 6 if(b & 1) ret = ret * tmp % p; 7 tmp = tmp * tmp % p; 8 b >>= 1; 9 } 10 return ret; 11 } 12 13 // bx = 1 (mod p) 14 LL modReverse(LL b, LL p) { 15 return fastModExp(b, p - 2, p); 16 }