Skip to content
This repository was archived by the owner on Nov 29, 2020. It is now read-only.

Commit ae979c4

Browse files
committed
Euclid.cpp
1 parent 5c78d0a commit ae979c4

File tree

2 files changed

+73
-0
lines changed

2 files changed

+73
-0
lines changed

Euclid.cpp

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
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+

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,8 @@
197197
| 30 | RecursiveFFT.cpp | Polynomial Multiply | 914 |
198198
| 30 | IterativeFFT.cpp | Iterative FFT | 917 |
199199
| 30 | IterativeFFT.cpp | Bit Reversal Copy | 918 |
200+
| 31 | Euclid.cpp | Euclid | 935 |
201+
| 31 | Euclid.cpp | Extended Euclid | 937 |
200202

201203
# Supplementary Files
202204
* `utils.h`: Utils

0 commit comments

Comments
 (0)