洛谷P1082 同余方程 题解

题目链接:https://www.luogu.com.cn/problem/P1082

题目大意:
求关于 \(x\) 的同余方程 ax≡1(mod b) 的最小正整数解。
告诉你 \(a,b\)\(x\)

解题思路:
直接套扩展GCD模板。

实现代码如下:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

void gcd(ll a , ll b , ll &d , ll &x , ll &y) {
    if(!b) {d = a; x = 1; y = 0;}
    else { gcd(b , a%b,d,y , x); y -= x * (a/b); }
}
ll inv(ll a , ll n) {
    ll d , x , y;
    gcd(a , n , d,  x , y);
    return d == 1 ? (x+n)%n : -1;
}

ll a, b;
int main() {
    cin >> a >> b;
    ll c = inv(a, b);
    cout << c << endl;
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/quanjun/p/12152278.html