【乘法逆元】
【乘法逆元】
注意:除法不能先取模!!!
定义
使用方法
关于取模
加法/乘法:直接取模
减法:+mod再取模
除法:乘逆元再取模
使用逆元的条件
题目中一般mod都是质数
计算逆元
qmi(b,mod-2,mod)
使用逆元
(a/b)%mod
=(a%mod)*(b的逆元)%mod
求解逆元
先判断互质
->求解a^p-2
#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
typedef pair<int,int> PII;
typedef long long ll;
ll abss(ll a){return a>0?a:-a;}
ll max_(ll a,ll b){return a>b?a:b;}
ll min_(ll a,ll b){return a<b?a:b;}
bool cmpll(ll a,ll b){return a>b;}
/*求a^p-2就行*/
ll qmi(ll a,ll k,ll p){
ll res=1;
while(k){
if(k&1) res=res*a%p;
k>>=1;//删去k的末位
a=a*a%p;
}
return res;
}
ll gcd(ll a,ll b){
return b?gcd(b,a%b):a;
}
int n,a,p;
signed main(){
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
cin>>n;
while(n--){
cin>>a>>p;
if(gcd(a,p)==1){//要判断是否互质!
ll res=qmi(a,p-2,p);
cout<<res<<endl;
}
else cout<<"impossible"<<endl;
}
return 0;
}
连续数字逆元的线性递推
https://www.luogu.com.cn/problem/P3811
void build(ll x,ll mod){
inv[1]=1;
for(int i=2;i<=n;i++){
inv[i]=(mod-inv[mod%i]*(mod/i)%mod);
}
}