[BJ-008]数学

· · 学习·文化课

1.gcd

而且 $gcd(a,b)$ 又等价于 $gcd(b,a \bmod b)$。证明如下: 设 $gcd(a,b)=d$,则 $a=dx$,$b=dy$。其中 $x,y$ 是正整数。 又则 $a \bmod b = dx \bmod dy$。 可以证明,辗转相除后的数的因子总是有**最大公约数**$d$。 ```cpp long long Gcd(int x,int y){ if(!y)return x; else return Gcd(y,x%y); } ``` ### 2.快速幂 题目算式:$a^b \bmod p$。 考虑 $b$ 的二进制上有 $1$ 的位表示 $2^k_{(10)}$,其中 $k$ 是正整数。 那么 $a^b=a^{2^1} \times p_1 \times ...\times a^{2^i} \times p_i$,其中 $p_i$ 表示 $b$ 二进制上第 $i$ 位有没有 $1$。`p[i]=b&(1<<i);`。 ```cpp long long Pow(ll x,ll y,ll z){ ll res=1; while(y){ if(y&1)res=res*a%p; a=a*a%p; y>>=1; } return res%p; } ``` ### 3.逆元 $a^{p-1} \equiv 1 \pmod p$,其中 $p$ 是质数,$a$ 是任意数(不包括 $0$)。 定义任意有理数 $a,x,i$,任意质数 $p$。 则有以下[同余方程](https://www.luogu.me/paste/7r38v53s#)。 [看这道模板题:](https://www.luogu.com.cn/problem/P3811) 既然 $ax \equiv 1 \pmod p$,那么根据**费马小定理**,$x=a^{p-2}$。 首先考虑朴素做法,快速幂求每个 $i^{p-2} \bmod p$,时间复杂度 $O(nlogn)$。$500$ ms显然`TLE`。 考虑优化,预处理出 $1$ 到 $n$ 每个数的阶乘。 再次考虑到,$(n!)^{p-2} \equiv \frac{1}{n!} \pmod p$,所以定义 $inv_i = \frac{1}{i!}$ 的**逆元**。 而求每个 $\frac{1}{i!}$ 的逆元,考虑倒序,每个`invf[i]=invf[i+1]*(i+1)%p;`。即 $\frac{1}{(i+1)!} \times (i+1)=\frac{1}{i!}$。 最后,对于每个 $i$,可以知道 $\frac{1}{i} \equiv i^{p-2} \pmod p$,并且可以知道 $\frac{1}{i} \equiv \frac{1}{n!} \times (n-1)! \pmod p$,所以,每个 $i$ 的逆元就可以用 $O(n)$ 的时间复杂度统计出来。 ```cpp #include<bits/stdc++.h> #define IMax 0x3f3f3f3f #define IMin -0x3f3f3f3f #define ULL unsigned long long #define BASE 131 #define pii pair<int,int> #define fir first #define sec second #define ll long long #define LMax LLONG_MAX #define LMin LLONG_MIN #define byzyx cin.tie(0)->ios::sync_with_stdio(0); using namespace std; inline void read(int &x){ int f=1;x=0;char s=getchar(); while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();} while(s>='0'&&s<='9'){x=x*10+s-'0';s=getchar();} x*=f; } const int N=3e6+5; ll n,p,fac[N],invf[N]; ll Pow(ll a,ll b,ll c){ ll res=1; while(b){ if(b&1)res=res*a%c; a=a*a%p; b>>=1; } return res; } signed main(void){ byzyx cin>>n>>p; fac[0]=1; for(int i=1;i<=n;i++)fac[i]=fac[i-1]*i%p; invf[n]=Pow(fac[n],p-2,p); for(int i=n-1;i>=1;i--)invf[i]=invf[i+1]*(i+1)%p; for(int i=1;i<=n;i++){ cout<<invf[i]*fac[i-1]%p<<'\n'; } return 0; } ```