当前位置: 代码迷 >> 综合 >> ZOJ 3609 Modular Inverse(乘法逆元)
  详细解决方案

ZOJ 3609 Modular Inverse(乘法逆元)

热度:12   发布时间:2023-12-08 10:42:43.0

题目链接:
ZOJ 3609 Modular Inverse
题意:
求ax = 1 (mod n),给出a,n的最小正数解x,如果不存在输出Not Exist.
分析:
用扩展欧几里德求乘法逆元。注意是最小正数解!而不是非负数解!

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
#include <climits>
#include <cmath>
#include <ctime>
#include <cassert>
#define IOS ios_base::sync_with_stdio(0); cin.tie(0);
using namespace std;
typedef long long ll;ll ex_gcd(ll a, ll b, ll& x, ll& y)
{if(b == 0) {x = 1, y = 0;return a;}ll d = ex_gcd(b, a % b, y, x);y -= a / b * x;return d;
}int main()
{int T;ll a, b;scanf("%d", &T);while(T--){scanf("%lld%lld", &a, &b);ll x, y;ll d = ex_gcd(a, b, x, y);if(d != 1) printf("Not Exist\n");else{ x = (x % b + b) % b;if(x == 0) x = b;printf("%lld\n", x);}}return 0;
}
  相关解决方案