不懂的点这里
a ∗ b + n ∗ t = 1 a*b + n *t = 1 a∗b+n∗t=1
long long ex_gcd(long long a,long long b,long long &x,long long &y)
{
if(b == 0)
{
x = 1;
y = 0;
return a;
}
long long m = ex_gcd(b,a%b,y,x);
y -= a/b * x;
return m;
}
int main()
{
long long a,b,x,y;
cin>>a>>b; //求a 关于b的逆元
if(ex_gcd(a,b,x,y)==1)
cout<<(x%b+b)%b<<endl;
else
cout<<"None"<<endl;
return 0;
}
long long qpow(long long a,long long b,long long m)//快速幂
{
long long ans = 1;
a %= m;
while(b > 0)
{
if(b & 1)
ans = (ans * a) % m;
a = a * a % m;
b >>= 1;
}
return ans;
}
long long Fermat(long long a,long long p)//前提p是质数
{
return qpow(a,p-2,p);
}
long long Euler(long long n)//求一个数的欧拉值
{
if(n == 1)
return 1;
long long ans = n;
for(int i = 2;i * i <= n; ++i)
{
if(n % i== 0)
{
while(n % i == 0)
n /= i;
ans = ans/i * (i-1);
}
}
if(n != 1)
ans = ans/n*(n-1);
return ans;
}
long long Euler_to_invers(long long a,long long b)//
{
return qpow(a,Euler(b)-1,b);
}
如果p是一个奇质数,则可以在o(n)时间内求出所有关于同余系关于p的逆元
证明如下
对p进行带余除法,求i的逆元
p = i ∗ k + t ( 0 < t < i ) p = i * k + t \ ( 0 < t < i) p=i∗k+t (0<t<i)
等式两边同时对关于p取模
于是 t = − i ∗ k ( m o d p ) t = -i * k ( mod \ p) t=−i∗k(mod p)
等式两边同时乘以 i n v ( i ) ∗ i n v ( t ) inv(i) * inv(t) inv(i)∗inv(t)
i n v ( i ) = − k ∗ i n v ( t ) ( m o d p ) inv(i) = -k * inv(t) ( mod\ p) inv(i)=−k∗inv(t)(mod p)
i n v ( i ) = ( p − k ∗ i n v ( t ) ) ( m o d p ) inv(i) = (p - k* inv(t)\ ) (mod\ p) inv(i)=(p−k∗inv(t) )(mod p)
i n v ( i ) = ( p − p / i ∗ i n v ( p % i ) ) ( m o d p ) inv(i) = (p - p \ / \ i * inv(p\ \% \ i ) ) (mod \ p) inv(i)=(p−p / i∗inv(p % i))(mod p)
这样就可以用一个数组存储关于p的所有逆元
int inv[10000];
int p;
cin>>p;
inv[1] = 1;
for(int i = 2;i < p; ++i)
{
inv[i] = (p - p/i*inv[p%i]%p)%p;
}
for(int i = 1;i < p; ++i)
cout<<inv[i]<<" ";
cout<<endl;
for(int i = 1;i < p; ++i)
cout<<i * inv[i] % p<<" ";
const int maxn = 1e5+10;
long long fac[maxn],invfac[maxn];
void init(int n){
fac[0] = 1;
for(int i = 1;i <= n; ++i) fac[i] = fac[i-1]*i%mod;
invfac[n] = qpow(fac[n],mod-2);
for(int i = n-1;i >= 0; --i) invfac[i] = invfac[i+1]*(i+1)%mod;
}