>Link
luogu P1082
>Description
给出 a , b a,b a,b,求 a x ≡ 1 ( m o d b ) ax≡1(modb) ax≡1(modb) 中 x x x 的最小值
>解题思路
题意转换,求
a
x
+
b
y
=
1
ax+by=1
ax+by=1 ,
x
x
x 的最小值
由这个式子可得,
1
1
1 是
g
c
d
(
a
,
b
)
gcd(a,b)
gcd(a,b) 的倍数,那么
g
c
d
(
a
,
b
)
gcd(a,b)
gcd(a,b) 就一定为
1
1
1
所以式子变成
a
x
+
b
y
=
g
c
d
(
a
,
b
)
ax+by=gcd(a,b)
ax+by=gcd(a,b),可以直接用扩展欧几里得了,要注意最后使得
x
x
x 为正数
>代码
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#define LL long long
using namespace std;
void ex_gcd (LL a, LL b, LL &x, LL &y)
{
if (!b)
{
x = 1, y = 0;
return;
}
LL X, Y;
ex_gcd (b, a % b, X, Y);
x = Y;
y = X - (a / b) * Y;
}
int main()
{
LL a, b, ans, y;
scanf ("%lld%lld", &a, &b);
ex_gcd (a, b, ans, y);
printf ("%lld", (ans + b) % b);
return 0;
}