1. 程式人生 > >求逆元

求逆元

spa != class return template 擴展 temp div 返回

1 利用擴展歐幾裏得求解

// ax=1 mod(n)
//返回-1表示不存在逆元
template<class T> T mod_reverse(T a,T n){
    T x,y,d;
    exgcd(a,n,d,x,y);
    if(d==1) return (x%n+n)%n;
    else return -1;
}

2 利用歐拉函數

template<class T> T fast_mod(T a,T b,T Mod){
    a%=mod;
    if(b==0) return 1;
    T ans=1,base=a;
    while
(b!=0){ if(b&1)ans=(ans*base)%Mod; base=(base*base)%Mod; b>>=1; } return ans; } // ax=1 mod(n) a與n互質 template<class T> T inv(T a,T n){ return fast_mod(a,n-2,n); }

求逆元