求逆元:
(m / q ) % x ,这里因为m / q 不一定为整数,所以构造一个新的式子: (m / q) % x = m * y % x, 这里的y就是要求的逆元
-
费马小定理加快速幂求逆元:
求法:原式变形为:
1 / q = y (%x)->
1 = y * q(%x) ->
由于x是质数,gcd(q,x) == 1,所以满足费马小定理,->
1 = q^(x-1) (%x)->
q^(x-1) = y * q (%x)->
y = q^(x-2) (%x)->
所以:(m / q) % x = m * q ^ (x - 2) % x


1 #include <iostream>
2 using namespace std;
3
4 typedef long long LL;
5
6 int qmi(int a, int b, int c){
7 LL res = 1;
8 while(b){
9 if(b & 1) res = res * a % c;
10 a = a * (LL)a % c;
11 b >>= 1;
12 }
13 return res;
14 }
15
16 int main(){
17 int n;cin >> n;
18 while(n --){
19 int a, p;cin >> a >> p;
20 if(a % p == 0) cout << "impossible" << endl;//a和p不是互质的
21 else cout << qmi(a, p - 2, p) << endl;
22 }
23 return 0;
24 }
end
来源:https://www.cnblogs.com/sxq-study/p/12257667.html
