exgcd
给出非负整数a,b;求的满足ax+by=1的最小非负整数x和整数y,若没有则输出sorry。
#include<cstdio>
#include<cctype>
#include<iostream>
#define rg register
#define int long long
using namespace std;
inline int read(){
rg int f = 0, x = 0;
rg char ch = getchar();
while(!isdigit(ch)) f |= (ch == '-'), ch = getchar();
while( isdigit(ch)) x = (x << 1) + (x << 3) + (ch ^ 48), ch = getchar();
return f? -x: x;
}
int a, b, x, y;
inline int exgcd(rg int a, rg int b, int &x, int &y){
if(!b){
x = 1, y = 0;
return a;
}
int d = exgcd(b, a%b, x, y);
int z = x;
x = y;
y = z - y * (a/b);
return d;
}
signed main(){
a = read(), b = read();
if(exgcd(a, b, x, y) == 1){
x %= b;
if(x < 0) x += b;
printf("%lld %lld", x, (1 - a * x) / b);
} else puts("sorry");
return 0;
}

浙公网安备 33010602011771号