AcWing 876. 快速幂求逆元 · znzryb
## 思路讲解
我们计算机嘛,这个推导对于我来说还是有点难了,不过结论很简单,就是**b^(m-2)为其乘法逆元**。
当然,你会说这个乘法逆元有什么用? [AcWing 886. 费马小定理, 快速幂, 求组合数 II ](/2025/03/30/20250330-81995ee4)
这不求组合数就有用了吗!
参考以下题解
[https://www.acwing.com/solution/content/16482/](https://www.acwing.com/solution/content/16482/)

## AC代码
[https://www.acwing.com/problem/content/submission/code_detail/40913617/](https://www.acwing.com/problem/content/submission/code_detail/40913617/)
```cpp
// Problem: 快速幂求逆元
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/878/
// Memory Limit: 64 MB
// Time Limit: 5000 ms
// by znzryb
//
// Powered by CP Editor (https://cpeditor.org)
#include <bits/stdc++.h>
#define FOR(i, a, b) for (int i = (a); i <= (b); ++i)
#define ROF(i, a, b) for (int i = (a); i >= (b); --i)
#define all(x) x.begin(),x.end()
#define CLR(i,a) memset(i,a,sizeof(i))
#define fi first
#define se second
#define pb push_back
#define SZ(a) ((int) a.size())
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll,ll> pll;
typedef array<ll,3> arr;
typedef double DB;
typedef pair<DB,DB> pdd;
typedef pair<ll,bool> plb;
constexpr ll MAXN=static_cast<ll>(1e6)+10,INF=static_cast<ll>(5e18)+3;
ll N,M,T,A[MAXN];
ll binpow(ll a,ll k,const ll &p){
ll res=1;
while(k>0){
if((k&1)==1) res=a*res%p;
a=a*a%p;
k>>=1;
}
return res;
}
inline void solve(){
ll a,p;
cin>>a>>p;
if(a%p==0) cout<<"impossible\n";
else cout<<binpow(a,p-2,p)<<"\n";
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);cout.tie(0);
cin>>T;
while(T--){
solve();
}
// solve();
return 0;
}
/*
AC
https://www.acwing.com/problem/content/submission/code_detail/40913617/
*/
```
## 心路历程(WA,TLE,MLE……)