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;
- }
本文详细介绍了扩展欧几里得算法,该算法不仅能够求解两数的最大公约数,还能找出一组解使得ax + by = gcd(a, b)成立。通过具体的代码实现展示了如何在实际应用中运用这一数学工具。
1183

被折叠的 条评论
为什么被折叠?



