For the detail explanation of the algorithm, refer to Programming Challenges.
Code:
- /***************************************************************************
- * Copyright (C) 2008 by Liu Kaipeng *
- * LiuKaipeng at gmail dot com *
- ***************************************************************************/
- /* @JUDGE_ID 00000 10104 C++ "Euclid Problem" */
- #include <algorithm>
- #include <cstdio>
- #include <cstring>
- #include <deque>
- #include <fstream>
- #include <iostream>
- #include <list>
- #include <map>
- #include <queue>
- #include <set>
- #include <stack>
- #include <string>
- #include <vector>
- using namespace std;
- /*
- * find gcd(a, b) and x, y such that a*x + b*y = gcd(a, b)
- */
- int gcd(int a, int b, int& x, int& y)
- {
- if (a < b) return gcd(b, a, y, x);
- if (b == 0) {
- x = 1;
- y = 0;
- return a;
- }
- int x1, y1;
- int g = gcd(b, a % b, x1, y1);
- x = y1;
- y = (x1 - a / b * y1);
- return g;
- }
- int main(int argc, char *argv[])
- {
- #ifndef ONLINE_JUDGE
- freopen((string(argv[0]) + ".in").c_str(), "r", stdin);
- freopen((string(argv[0]) + ".out").c_str(), "w", stdout);
- #endif
- for (int a, b; cin >> a >> b; ) {
- int x, y;
- int g = gcd(a, b, x, y);
- cout << x << ' ' << y << ' ' << g << '/n';
- }
- return 0;
- }