ZOJ ~ 3609 ~ Modular Inverse (扩展欧几里得,乘法逆元)

题意

求a*x ≡ 1(mod m),求最小的正整数 x ,如果没有解输出 “Not Exist”。

思路

求乘法逆元。a*x ≡ 1(mod m)转化为 ax+my=1,求最小的正!整数 x 。

#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
void exgcd(int a, int b, int& d, int& x, int& y)
{
    if (!b) { d=a; x=1; y=0; }
    else { exgcd(b, a%b, d, y, x); y -= x*(a/b); }
}
int cal(int a, int b, int c)
{
    int GCD, x0, y0;
    exgcd(a, b, GCD, x0, y0);
    if (c%GCD) return -1;
    x0 *= c/GCD;
    int ans = (x0%b+b)%b;
    return ans?ans:b;
}
int main()
{
    int T; scanf("%d", &T);
    while (T--)
    {
        int a, m; scanf("%d%d", &a, &m);
        int ans = cal(a, m, 1);
        if (ans != -1) printf("%d\n", ans);
        else printf("Not Exist\n");
    }
    return 0;
}
/*
3
3 11
4 12
5 13
*/


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值