UVa Problem Solution: 10104 - Euclid Problem

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


For the detail explanation of the algorithm, refer to Programming Challenges.

Code:
  1. /***************************************************************************
  2.  *   Copyright (C) 2008 by Liu Kaipeng                                     *
  3.  *   LiuKaipeng at gmail dot com                                           *
  4.  ***************************************************************************/
  5. /* @JUDGE_ID 00000 10104 C++ "Euclid Problem" */
  6. #include <algorithm>
  7. #include <cstdio>
  8. #include <cstring>
  9. #include <deque>
  10. #include <fstream>
  11. #include <iostream>
  12. #include <list>
  13. #include <map>
  14. #include <queue>
  15. #include <set>
  16. #include <stack>
  17. #include <string>
  18. #include <vector>
  19. using namespace std;
  20.      
  21. /*
  22.  * find gcd(a, b) and x, y such that a*x + b*y = gcd(a, b) 
  23.  */
  24. int gcd(int a, int b, int& x, int& y)
  25. {
  26.   if (a < b) return gcd(b, a, y, x);
  27.   if (b == 0) {
  28.     x = 1;
  29.     y = 0;
  30.     return a;
  31.   }
  32.   
  33.   int x1, y1;
  34.   int g = gcd(b, a % b, x1, y1);
  35.   x = y1;
  36.   y = (x1 - a / b * y1);
  37.   return g;
  38. }
  39.           
  40. int main(int argc, char *argv[])
  41. {
  42. #ifndef ONLINE_JUDGE
  43.   freopen((string(argv[0]) + ".in").c_str(), "r", stdin);
  44.   freopen((string(argv[0]) + ".out").c_str(), "w", stdout);
  45. #endif
  46.   for (int a, b; cin >> a >> b; ) {
  47.     int x, y;
  48.     int g = gcd(a, b, x, y);
  49.     cout << x << ' ' << y << ' ' << g << '/n';
  50.   }
  51.   return 0;
  52. }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值