TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
extended_euclid_algorithm.cpp
Go to the documentation of this file.
1
12#include <algorithm> // for swap function
13#include <iostream>
14#include <cstdint>
15
24template <typename T, typename T2>
25inline void update_step(T *r, T *r0, const T2 quotient) {
26 T temp = *r;
27 *r = *r0 - (quotient * temp);
28 *r0 = temp;
29}
30
41template <typename T1, typename T2>
42void extendedEuclid_1(T1 A, T1 B, T1 *GCD, T2 *x, T2 *y) {
43 if (B > A)
44 std::swap(A, B); // Ensure that A >= B
45
46 T2 s = 0, s0 = 1;
47 T2 t = 1, t0 = 0;
48 T1 r = B, r0 = A;
49
50 while (r != 0) {
51 T1 quotient = r0 / r;
52 update_step(&r, &r0, quotient);
53 update_step(&s, &s0, quotient);
54 update_step(&t, &t0, quotient);
55 }
56 *GCD = r0;
57 *x = s0;
58 *y = t0;
59}
60
70template <typename T, typename T2>
71void extendedEuclid(T A, T B, T *GCD, T2 *x, T2 *y) {
72 if (B > A)
73 std::swap(A, B); // Ensure that A >= B
74
75 if (B == 0) {
76 *GCD = A;
77 *x = 1;
78 *y = 0;
79 } else {
80 extendedEuclid(B, A % B, GCD, x, y);
81 T2 temp = *x;
82 *x = *y;
83 *y = temp - (A / B) * (*y);
84 }
85}
86
88int main() {
89 uint32_t a, b, gcd;
90 int32_t x, y;
91 std::cin >> a >> b;
92 extendedEuclid(a, b, &gcd, &x, &y);
93 std::cout << gcd << " " << x << " " << y << std::endl;
94 extendedEuclid_1(a, b, &gcd, &x, &y);
95 std::cout << gcd << " " << x << " " << y << std::endl;
96 return 0;
97}
void extendedEuclid_1(T1 A, T1 B, T1 *GCD, T2 *x, T2 *y)
void update_step(T *r, T *r0, const T2 quotient)
void extendedEuclid(T A, T B, T *GCD, T2 *x, T2 *y)
int main()
Main function.
int gcd(int num1, int num2)