【逆元】求解逆元的方法

版权声明:侵删 [email protected] https://blog.csdn.net/weixin_43350051/article/details/88084822

求逆元的方法:

注: a和p只有在互素的情况下才存在逆元

1.快速幂+费马小定理/欧拉方程:

(a^(mod-2)+函数中取余mod的结果表示逆元)

代码:

#include<stdio.h>
typedef long long int LL;
LL inv;
LL qpow(LL a,LL q,LL mod)       //关于快速幂上面都有 不详细说了 但要注意传参是mod-2
{  
    LL ans;
    ans=1;
    while(q){
        if(q%2){
            ans=ans*a%mod;
        }
        a=a*a%mod;
        q/=2;
    }
    return ans;
}
LL getinv(LL a,LL mod)
{
    return qpow(a,mod-2,mod);
}


int main()
{
    LL a,mod;
    scanf("%lld%lld",&a,&mod);
    inv=getinv(a,mod);
    printf("%lld\n",inv%mod);
    return 0;
}

2. 拓展欧几里得求逆元:

(a和b=mod求特解表示逆元)

代码:

#include<stdio.h>
typedef long long int LL;
LL GCD;
LL exgcd(LL a,LL b,LL &x,LL &y)
{
    if(!b){
        x=1;y=0;return a;
    }
    GCD=exgcd(b,a%b,y,x);
    y-=a/b*x;
    return GCD;
}
LL getinv(LL a,LL mod)
{
    LL x,y;
    GCD=exgcd(a,mod,x,y);                //让b=mod 然后用拓展欧几里得公式求解
    return GCD==1? (x%mod+mod)%mod:0;
}
int main()
{
    LL a,mod,c;
    scanf("%lld%lld",&a,&mod);
    c=getinv(a,mod);
    if(c){
        printf("%lld\n",c);
    }
    else{
        printf("error!\n");
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43350051/article/details/88084822