From f4e1f7f58a2f0ff66462ebc8a16d2a0b32dbc7b3 Mon Sep 17 00:00:00 2001 From: aniakubik Date: Fri, 25 Oct 2019 17:42:51 +0200 Subject: [PATCH] extended eucildean algorithm --- Math/extendedEuclidian.cpp | 51 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Math/extendedEuclidian.cpp diff --git a/Math/extendedEuclidian.cpp b/Math/extendedEuclidian.cpp new file mode 100644 index 000000000..ad9846a87 --- /dev/null +++ b/Math/extendedEuclidian.cpp @@ -0,0 +1,51 @@ +#include +#include + +using namespace std; + +/* + for numbers a, b returns x, y such as x * a + y * b = gcd(a,b) +*/ + +pair extendedEuclidian(int a, int b) { + int a_old = a, b_old = b; + if(a < b) swap(a,b); + + int x = 0, y = 1, old_x = 1, old_y = 0; + + int quotient, residue; + while (b) { + quotient = a / b; + residue = a % b; + + a = b; + b = residue; + + int temp; + + temp = x; + x = old_x - quotient * x; + old_x = temp; + + + temp = y; + y = old_y - quotient * y; + old_y = temp; + } + + if(b_old > a_old) swap(old_x, old_y); + + return make_pair(old_x, old_y); + +} + +int main() { + + int a, b; + cin >> a >> b; + pair result = extendedEuclidian(a, b); + + cout<< result.first << " " << result.second; + + +} \ No newline at end of file