题意:已知x*a + y*b = 1,给出a和b,让你求出最小的非负x以及对应的y,无解输出sorry。
思路:扩展欧几里得求出x和y,根据定理——gcd(x, y) == 1,ax == c(mod b)在[0, b-1]上有解。
转化式子x*a + b*y = 1 -> a*x == 1 (mod b)。
对欧几里得求出的x,最小的非负x = (x%b + b)%b,然后代入求出y。
#include <cstdio> #include <cstring> #include <cmath> #include <cstdlib> #include <algorithm> #include <map> #include <string> #include <vector> #define lson o<<1|1, l, mid #define rson o<<1, mid+1, r #define ll o<<1 #define rr o<<1|1 #define INF 0x3f3f3f3f #define eps 1e-8 #define debug printf("1\n") #define MAXN 1010 #define MAXM 100000 #define LL long long #define CLR(a, b) memset(a, (b), sizeof(a)) #define W(a) while(a--) #define Ri(a) scanf("%d", &a) #define Ri2(a, b) scanf("%d%d", &a, &b) #define Pi(a) printf("%d\n", (a)) #define Pi2(a, b) printf("%d %d\n", a, b) #define Rl(a) scanf("%lld", &a) #define Rl2(a, b) scanf("%lld%lld", &a, &b) #define Pl(a) printf("%lld\n", (a)) #define Pl2(a, b) printf("%lld %lld\n", a, b) #define Rs(a) scanf("%s", a) #define Rs2(a, b) scanf("%s%s", a, b) #define Ps(a) printf("%s\n", (a)) #define Ps2(a, b) printf("%s %s\n", a, b) #define FOR(i, l, r) for(int i = (l); i <= (r); i++) #define FOR1(i, l, r) for(int i = (l); i < (r); i++) #define MOD 1000000007 using namespace std; LL gcd(LL a, LL b){ return b == 0 ? a : gcd(b, a%b); } void exgcd(LL a, LL b, LL &d, LL &x, LL &y) { if(b == 0) {d = a, x = 1, y = 0;} else { exgcd(b, a%b, d, y, x); y -= x * (a/ b); } } int main() { LL a, b; while(~Rl2(a, b)) { if(gcd(a, b) != 1) { printf("sorry\n"); continue; } LL d, x, y; exgcd(a, b, d, x, y); x = (x % b + b) % b; y = (1 - a*x) / b; Pl2(x, y); } return 0; }