求模的逆元

欧拉函数Φ(n)

一些定理:

欧拉定理
an都是正整数,且an互素,则aΦ(n) ≡ 1 (mod n)
ab (mod n) = a(b % Φ(n) + Φ(n)) (mod n)
ab (mod n) = a(b % Φ(n))(mod n),gcd(a,n)=1

费马小定理(欧拉定理弱化形式)
a是正整数,p是素数,且ap互素,pow(a,p-1) ≡ 1 (mod p)(因为Φ(p)=p-1)

逆元

a*b=1modm)则称作ba在模m下的逆元。记作a^-1=b(mod m)
显然只有(a,m)=1时存在逆元。
性质: a^-1=b(mod m)
b^-1=a(mod m)
a*b=1(mod m)
a^-1=b+km(mod m)
m/a=m*b(mod m)

求逆元

1.a*x+b*y=1;解方程得x为a在mod b下的逆元。(要求gcd(a,b)=1)(exgcd方法)
#include 
#include 
using namespace std;
int x,y,d,a,b;//a*x + b*y=GCD(a,b)
//d为答案
void exgcd(int a, int b, int &d, int &x, int &y)
{
    if(!b){d=a;x=1;y=0;}
    else {exgcd(b, a%b, d, y, x); y-=x*(a/b);}
}
int main()
{
    scanf("%d%d",&a,&b);
    exgcd(a,b,d,x,y);
    printf("x=%d y=%d d=%d\n",x,y,d);
    return 0;
}


2.a^( Φ( m) -1)=b; 注意 gcd ( a,m )=1; 特别地,当 p 为素数时, a^(p-2)=b;
(快速幂)
LL po(LL k)
{
    LL ret=1;
    LL m=MOD-2;
    while(m)
    {
        if(m&1LL)ret=ret*k%MOD;
        k=k*k%MOD;
        m>>=1LL;
    }
    return ret;
}




你可能感兴趣的:(数学)