1.扩展欧几里得算法
ll exgcd(ll a,ll b,ll &x,ll &y) { if(!b) { x = (ll)1,y = (ll)0; return a; } ll r = exgcd(b,a%b,x,y); ll t = x; x = y; y = t - a/b*y; return r; } //计算模n下a的逆,如果不存在逆,返回-1 ll inv(ll a,ll n) { ll d,x,y; d = exgcd(a,n,x,y); return d == 1 ? (x+n)%n : -1; }
2.快速幂法
ll fastm(ll n,ll k,ll MOD) { ll res = 1LL; n %= MOD; while(k) { if(k&1) res = (res*n)%MOD; k >>= 1; n = n*n%MOD; } return res; } ll Inv(ll n,ll MOD) { return fastm(n,MOD-2,MOD); }