|
| 1 | +// |
| 2 | +// algorithm - some algorithms in "Introduction to Algorithms", third edition |
| 3 | +// Copyright (C) 2018 lxylxy123456 |
| 4 | +// |
| 5 | +// This program is free software: you can redistribute it and/or modify |
| 6 | +// it under the terms of the GNU Affero General Public License as |
| 7 | +// published by the Free Software Foundation, either version 3 of the |
| 8 | +// License, or (at your option) any later version. |
| 9 | +// |
| 10 | +// This program is distributed in the hope that it will be useful, |
| 11 | +// but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | +// GNU Affero General Public License for more details. |
| 14 | +// |
| 15 | +// You should have received a copy of the GNU Affero General Public License |
| 16 | +// along with this program. If not, see <https://www.gnu.org/licenses/>. |
| 17 | +// |
| 18 | + |
| 19 | +#ifndef MAIN |
| 20 | +#define MAIN |
| 21 | +#define MAIN_Euclid |
| 22 | +#endif |
| 23 | + |
| 24 | +#ifndef FUNC_Euclid |
| 25 | +#define FUNC_Euclid |
| 26 | + |
| 27 | +#include <cassert> |
| 28 | +#include "utils.h" |
| 29 | + |
| 30 | +template <typename T> |
| 31 | +T Euclid(T a, T b) { |
| 32 | + if (b == 0) |
| 33 | + return a; |
| 34 | + else |
| 35 | + return Euclid(b, a % b); |
| 36 | +} |
| 37 | + |
| 38 | +template <typename T> |
| 39 | +T ExtendedEuclid(T a, T b, T& x, T& y) { |
| 40 | + if (b == 0) { |
| 41 | + x = 1; |
| 42 | + y = 0; |
| 43 | + return a; |
| 44 | + } else { |
| 45 | + T xx, yy; |
| 46 | + T dd = ExtendedEuclid(b, a % b, xx, yy); |
| 47 | + x = yy; |
| 48 | + y = xx - (a / b) * yy; |
| 49 | + return dd; |
| 50 | + } |
| 51 | +} |
| 52 | +#endif |
| 53 | + |
| 54 | +#ifdef MAIN_Euclid |
| 55 | +int main(int argc, char *argv[]) { |
| 56 | + const size_t n = get_argv(argc, argv, 1, 16); |
| 57 | + using T = long long int; |
| 58 | + std::random_device rd; |
| 59 | + std::uniform_int_distribution<T> dis(0, 1 << n); |
| 60 | + T a = get_argv(argc, argv, 2, dis(rd)); |
| 61 | + T b = get_argv(argc, argv, 3, dis(rd)); |
| 62 | + T x, y; |
| 63 | + T d = ExtendedEuclid(a, b, x, y); |
| 64 | + assert(d == Euclid(a, b)); |
| 65 | + assert(d == a * x + b * y); |
| 66 | + std::cout << d << " = gcd(" << a << ", " << b << ") = " |
| 67 | + << a << " * " << x << " + " << b << " * " << y << std::endl; |
| 68 | + return 0; |
| 69 | +} |
| 70 | +#endif |
| 71 | + |
0 commit comments