HDU1576 A/B 求乘法逆元模版

HDU1576A/B

ABmod9973
已知 gcd(B,9973)=1 ,所以 AB(mod9973)=AB1(mod9973) ,重在求乘法逆元:

由于 B9973=1 ,利用 Fermat 小定理最简单,逆元即为 Bmod2
AC代码:

/**************************************************************
* By: Xingxing
* Date: 2016-09-26
* Address: http://blog.csdn.net/legend_pawn?viewmode=contents
**************************************************************/
#include <iostream>
#include <cstdio>
typedef long long ll;
const int mod=9973;
using namespace std;
ll quickpow(ll a,ll b){
    int res=1;
    while(b>0){
        if(b&1)
            res=res*a%mod;
        b=b>>1;
        a=(a%mod)*(a%mod)%mod;
    }
    return res;
}
int main(){
    //freopen("input.txt","r",stdin);
    int T;
    cin>>T;
    while(T--){
        int n,b;
        scanf("%d%d",&n,&b);
        ll ans;
        ans=n*quickpow(b,9971)%mod;
        cout<<ans<<endl;
    }
    return 0;
}

另一种方法是扩展欧几里得求乘法逆元,即求解不定方程 b1b+9973y=1

AC代码:

/**************************************************************
* By: Xingxing
* Date: 2016-09-26
* Address: http://blog.csdn.net/legend_pawn?viewmode=contents
**************************************************************/
#include <iostream>
#include <cstdio>
typedef long long ll;
const int MOD=9973;
using namespace std;
ll extend_gcd(ll a,ll b,ll &x,ll &y){
    if(a==0 &&b==0)
        return -1;
    if(b==0){
        x=1;y=0;return a;
    }
    ll d=extend_gcd(b,a%b,y,x);
    y-=a/b*x;
    return d;
}
ll mod_reserve(ll a){
    ll x,y;
    ll d=extend_gcd(a,MOD,x,y);
    if(d==1)
        return (x+MOD)%MOD;
    else
        return -1;
}
int main(){
    //freopen("input.txt","r",stdin);
    int T;
    scanf("%d",&T);
    while(T--){
        int n,b;
        scanf("%d%d",&n,&b);
        ll ans;
        ans=(n*(mod_reserve(b)%MOD))%MOD;
        cout<<ans<<endl;
    }
    return 0;
}

最后一种:
要求 求 1,2,,p1modp 的逆元,然后就看到了一个 O(n) 的做法
这个做法实际上是这样的,首先 111  (mod p)
然后我们设: p=ki+r,r<i,1<i<p
再将这个算式放到 modp 的意义下得到:

kr+i0  (mod p)

两边同时乘上 i1,r1
kr1+i10     (mod p)i1kr1     (mod p)i1pip (mod i)     (mod p)

代码:

A[i] = -(p / i) * A[p % i];
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值