ZOJ Modular Inverse(扩展欧几里得求最小逆元)

题目链接:http://acm.zju.edu.cn/onlinejudge/showRuns.do?contestId=1

模型:求最小逆元。

分析:m不能确保是素数,因此费马小定理+快速幂不好用,(好像可以有欧拉定理),这里用扩展欧几里得模板,详见代码。

注意事项:最后结果要确保是最小正整数。

#include<iostream>
#include<cstdio>
#define ll long long
using namespace std;
ll exgcd(ll a,ll b,ll &x,ll &y)
{
    if(!b)
    {
        x=1;
        y=0;
        return a;
    }
    ll ans=exgcd(b,a%b,x,y);
    ll temp=x;
    x=y;
    y=temp-a/b*y;
    return ans;

}
int main()
{
    int t;
    cin>>t;
    while(t--)
    {
        ll a,m,x,y,c=1;
        cin>>a>>m;
        ll gcd=exgcd(a,m,x,y);
        if(gcd==1)//有整数解充要条件:c%GCD(a,b)==0,这里c为1,因此只有GCD==1时成立;
        {
            x=x%m;
            if(x<=0)x+=m;
            cout<<x<<endl;//如果写成x=(x%m+m)%m,则对于ans为零的情况无法判断;
        }
        else
        {
            cout<<"Not Exist"<<endl;
        }

    }
    return 0;

}

猜你喜欢

转载自blog.csdn.net/qq_41661919/article/details/81453100