题意:给两个非负整数 a 和 b,要找到一个非负整数 x 和一个整数 y,使得满足 x×a+y×b=1。
思路:用扩展欧几里得,因为要求 x 非负,所以可以把式子写成 x×a+y×b+a×b−a×b=a×(b+x)+b×(y−a)=1。欧几里得算出 x 和 y 后还要判断下 x,如果 x 小于 0,则用上面的推导式分别给 x 和 y 加上 b 和 -a 就好。
代码:
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<stack>
#include<queue>
#include<utility>
#include<vector>
#include<cmath>
#include<set>
#include<map>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long LL;
LL ExtendGcd(LL a, LL b, LL& x, LL& y)
{
LL r;
if(b == 0){
x = 1;
y = 0;
return a;
}
else{
r = ExtendGcd(b, a%b, y, x);
y -= (a/b)*x;
}
return r;
}
int main()
{
LL a, b;
while(scanf("%lld%lld", &a, &b) == 2){
LL x, y;
if(ExtendGcd(a, b, x, y) == 1){
while(x < 0){
x += b;
y -= a;
}
printf("%lld %lld\n", x, y);
}
else{
printf("sorry\n");
}
}
return 0;
}