求逆的模板(求逆本质上就是在mod 的状态下除一个数)

2019-04-14 15:25发布

//接口:inv(a,n) a : 待求逆的数,n表示mod //没有逆元,返回-1 void gcd(LL a,LL b,LL &d,LL &x,LL &y) { if(!b){d = a;x = 1;y = 0;} else {gcd(b,a% b,d,y,x); y-= x * (a / b);} } LL inv(LL a,LL n) { LL d,x,y; gcd(a,n,d,x,y); return d == 1 ? (x + n) % n : -1; }