逆元求解(模板)

在模p的前提下,a的逆元存在的充要条件是a和p互素,即gcd(a,b)=1

//拓展欧几里德算法求逆元
typedef long long ll;
void gcd(ll a, ll b, ll &d, ll& x, ll& y) {
	if (0 == b) { d = a; x = 1; y = 0; }
	else { gcd(b, a%b, d, y, x); y -= x*(a / b); }
}
//计算模p下a的逆元,如果逆元不存在则返回-1
ll inv(ll a, ll p) {
	ll d, x, y;
	gcd(a, p, d, x, y);
	return d == 1 ? (x + p) % p : -1;
}
//欧拉函数求逆元,模p下a的逆元存在,那么a的逆元就是a^(phi(p)-1)(mod p)
//当p为素数时,a的逆元为a^(p-2)(mod p),用快速幂求解
typedef long long ll;
ll pow_mod(ll x, int n, ll mod) {
	ll ans = 1;
	while (n) {
		if (n & 1) ans = (ans * x) % mod;
		x = (x * x) % mod;
		n >>= 1;
	}
	return ans;
}
//计算模p下a的逆元,调用前保证p是素数
ll inv(ll a, ll p) {
	return pow_mod(a, p - 2, p);
}

逆元的线性递推公式
*inv(i) = (M-M/i)inv(M%i)%M
初始化inv(1)=1进行递推,注意1M所有整数的逆元还是对应着1M中的所有整数

typedef long long ll;
const int maxn=100050;
ll inv[maxn];

void getInv(ll p){
	inv[1]=1;
	for(int i=2;i<maxn;i++){
        inv[i]=(p-(p/i))*inv[p%i]%p;
    }
}
posted @ 2018-02-25 20:23  不想吃WA的咸鱼  阅读(244)  评论(0编辑  收藏  举报