数论求逆元的三种方法

扩展欧几里德算法



//非递归的扩展欧几里德算法  
//返回a、b的gcd,同时x、y满足ax+by=gcd  
int_t exEuclid(int_t a,int_t b,int_t&x,int_t&y){  
    int_t x0 = 1, y0 = 0;  
    int_t x1 = 0, y1 = 1;  
    x = 0; y = 1;  
    int_t r = a % b;  
    int_t q = ( a - r ) / b;  
    while( r ){  
        x = x0 - q * x1;  
        y = y0 - q * y1;  
        x0 = x1; y0 = y1;  
        x1 = x; y1 = y;  
        a = b; b = r; r = a % b;  
        q = ( a - r ) / b;  
    }  
    return b;  
}  
//求a相对于p的逆元,a、p互质才存在逆元  
int_t inv(int_t a,int_t p){  
    int_t x,y;  
    int_t r = exEuclid(a,p,x,y);  
    if ( r != 1 ) return 0;  
    x = x % p;  
    if ( x < 0 ) x += p;  
    return x;  
}  


费马小定理

//计算a^b%mod
llt powerMod(llt a,llt b,llt mod){
    llt ret = 1LL;
    a %= mod;
    while( b ){
        if ( b & 1LL ) ret = (ret*a)%mod,--b;
        b >>= 1LL;
        a = multiMod(a,a,mod);
    }
    return ret;
}
llt inv( int x ,int mod ){
    return powerMod( x, mod-2 ,mod );
}




线性筛逆元

这个做法实际上是这样的,首先  111(modp) 1−1≡1(modp)

然后我们设  p=ki+r, r<i, 1<i<p

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值