当前位置: 代码迷 >> 综合 >> B - exgcd
  详细解决方案

B - exgcd

热度:76   发布时间:2023-12-15 06:38:01.0

给出2个数M和N(M < N),且M与N互质,找出一个数K满足0 < K < N且K * M % N = 1,如果有多个满足条件的,输出最小的。

Input

输入2个数M, N中间用空格分隔(1 <= M < N <= 10^9)

Output

输出一个数K,满足0 < K < N且K * M % N = 1,如果有多个满足条件的,输出最小的。

Sample Input

2 3

Sample Output

2
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <vector>
#include <queue>
#include <stack>
#include <map>using namespace std;typedef long long ll;
long long ans, t, n, m, cnt;
string str, s;
vector<int> vec;
stack<long long> sn;
stack<char> sc;
struct node {int x, y;
} no[2005];
long long gcd(long long a, long long b) {return b ? gcd(b, a % b) : a;
}
void exgcd(long long a, long long b, long long &x, long long &y) {if(b == 0) {x = 1;y = 0;} else {exgcd(b, a % b, y, x);y -= (a / b) * x;}
}
int main() {while(scanf("%d %d", &n, &m) == 2) {long long x, y;exgcd(n, m, x, y);long long ans = (x % m + m) % m;printf("%lld\n", ans);}return 0;
}