线性求逆元 P3811 【模板】乘法逆元 题解
题目大意
求 \(1-N\) 的逆元,要求 \(O(n)\)
问题求解
大致的推导是这个样子
我们设
\[p=k\times i +r
\]
\[\Rightarrow k\times i+r\equiv0(\bmod p)
\]
两边除去\(i^{-1}\times r^{-1}(\bmod p)\),就变成
\[\Rightarrow k\times r^{-1}+i^{-1}\equiv0(\bmod p)
\]
移项
\[\Rightarrow i^{-1} \equiv -k\times r^{-1}
\]
由于 \(p=k\times i +r\) 可知
\[k=p/i,r=p\% i
\]
代入
\[\Rightarrow i^{-1} \equiv -p/i\times (p\% i)^{-1}
\]
由于\(C++\)中摸的性质,可能会出负数,我们将两边都加上\(p\)
\[\Rightarrow i^{-1} \equiv (p-p/i)\times (p\% i)^{-1}
\]
\[\Rightarrow i^{-1} = (p-p/i)\times (p\% i)^{-1}\%p
\]
用\(inv[i]\)来代表逆元,所以
\[\Rightarrow inv[i]=(p-p/i)\times inv[p\%i] \%p
\]
就可以线性求逆元了
当然如果你觉得上面的东西很难记住,就可以使用下面的方法
地球人都知道怎么推\(n!^{-1}\)
所以
\[n^{-1}=n! \times (n+1)!^{-1}
\]
代码实现
#pragma GCC optimize(2)
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
const int maxn=3e6+5;
int N,a[maxn],p;
LL inv[maxn];
struct IO{
static const int S=1<<21;
char buf[S],*p1,*p2;int st[105],Top;
~IO(){clear();}
inline void clear(){fwrite(buf,1,Top,stdout);Top=0;}
inline void pc(const char c){Top==S&&(clear(),0);buf[Top++]=c;}
inline char gc(){return p1==p2&&(p2=(p1=buf)+fread(buf,1,1<<21,stdin),p1==p2)?EOF:*p1++;}
inline IO&operator >> (char&x){while(x=gc(),x==' '||x=='\n'||x=='r');return *this;}
template<typename T>inline IO&operator >> (T&x){
x=0;bool f=0;char ch=gc();
while(ch<'0'||ch>'9'){if(ch=='-') f^=1;ch=gc();}
while(ch>='0'&&ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=gc();
f?x=-x:0;return *this;
}
inline IO&operator << (const char c){pc(c);return *this;}
template<typename T>inline IO&operator << (T x){
if(x<0) pc('-'),x=-x;
do{st[++st[0]]=x%10,x/=10;}while(x);
while(st[0]) pc('0'+st[st[0]--]);pc('\n');
return *this;
}
}fin,fout;
int main(){
freopen("P3811.in","r",stdin);
freopen("P3811.out","w",stdout);
fin>>N>>p;
inv[1]=1;fout<<inv[1];
for(int i=2;i<=N;i++)inv[i]=inv[p%i]*(p-p/i)%p,fout<<inv[i];
return 0;
}