给出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<cstdio>
typedef long long ll;
ll extend_gcd(ll a, ll b, ll &x, ll &y)
{
if (b == 0)
{
x = 1, y = 0;
return a;
}
else
{
ll r = extend_gcd(b, a % b, y, x);
y -= x * (a / b);
return r;
}
}
ll inv(ll a, ll n)
{
ll x, y;
extend_gcd(a, n, x, y);
x = (x % n + n) % n;
return x;
}
int main ()
{
int m, n;
scanf ("%d %d", &m, &n);
printf ("%lld\n", inv(m, n));
return 0;
}