求逆元——数学知识
1.快速幂求逆元:
使用前提:求a模p的乘法逆元时,如果用快速幂(费马小定理),那就必须保证p是质数,且a不是p的倍数。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 int n; 5 ll qmi(ll a,ll b,ll p) 6 { 7 ll res=1; 8 while(b) 9 { 10 if(b&1)res=res*a%p; 11 b>>=1; 12 a=a*a%p; 13 } 14 return res; 15 } 16 17 int main() 18 { 19 scanf("%d",&n); 20 while(n--) 21 { 22 ll a,p; 23 scanf("%lld%lld",&a,&p); 24 if(a%p==0)puts("impossible"); 25 else printf("%lld\n",qmi(a,p-2,p)); 26 } 27 28 return 0; 29 }