HDU 2669
题目大意:
已知线性方程ax+by=1; 输入a, b的值, 要求输出整数解x, y的值(输出x, y的最小整数解), 若没有解, 输出"sorry".
分析:
求线性方程的解用扩展欧几里得算法,令gcd(a,b)=d, 如果1是d的倍数表示方程有解, 否则无解.
代码如下:
1 #include <iostream>
2 #include <cstdio>
3 #include <cstring>
4 #include <fstream>
5 #include <ctime>
6 #include <cmath>
7 #include <cstdlib>
8 #include <algorithm>
9 #include <set>
10 #include <map>
11 #include <list>
12 #include <stack>
13 #include <queue>
14 #include <iterator>
15 #include <vector>
16
17 using namespace std;
18
19 #define LL long long
20 #define INF 0x3f3f3f3f
21 #define MOD 1000000007
22 #define MAXN 10000010
23 #define MAXM 1000010
24
25
26 LL extend_gcd(LL a, LL b, LL &x, LL &y)
27 {
28 if(b == 0)
29 {
30 x = 1;
31 y = 0;
32 return a;
33 }
34 else
35 {
36 LL r = extend_gcd(b, a%b, y, x);
37 y -= x*(a/b);
38 return r;
39 }
40 }
41
42
43 int main()
44 {
45 int a, b;
46 while(scanf("%d%d", &a, &b)==2)
47 {
48 LL t, p;
49 LL ans = extend_gcd(a, b, t, p);
50 if(1%ans)
51 printf("sorry\n");
52 else
53 {
54 LL x = 1*t/ans; //特解
55 x = (x%(b/ans)+(b/ans))%(b/ans); //最小整数解
56 LL y = (1-a*x)/b;
57 printf("%lld %lld\n", x, y);
58 }
59 }
60
61 return 0;
62 }