线性筛逆元
讲解
令\(f[i]\)为\(i\)在取模\(p\)下的逆元
证明\(f[i]=p-f[p\%i]*(p/i)\%p\),理由如下:
part1
首先我们要证明\(f[i]=-f[p-i]\)
\(\because f[i]*i=1\)
\(\therefore f[i]*(-i)=-1\)
\(-i\)是什么?是i的相反数!在取模\(p\)意义下,\(i\)的相反数是多少?\(p-i\)!
\(\therefore f[i]*(p-i)=-1\)
\(\therefore f[i]=-f[p-i]\)(两边同时乘以\(p-i\)的逆元)
part2
其次我们要证明\(f[i]=f[i*k]*k\)
\(\because f[i*k]*i*k=1\)
\(\therefore f[i*k]*k=f[i]\)
finally
令\(p=k*i+b\)
\(f[i]=f[i*k]*k=-f[p-i*k]*k=-f[b]*k\)
因为\(-f[b]*k\)是个负数,所以我们需要对其进行处理
\(\therefore f[i]=p-f[b]*k\%p=p-f[p\%i]*(p/i)\%p\)
代码
inv[1] = 1;
for(int i = 2;i <= n;++ i) inv[i] = MOD - 1ll * inv[MOD % i] * (MOD / i) % MOD;