Algoteka
Log in to submit your own samples!

Extended Euclidean Algorithm

Problem by oml1111
# Tech tags Title Creator Created date
1 0
2022-11-23 21:36
View all samples for this language (1 verified and 0 unverified)

O(log (a+b)) Recursive solution | C++ |

By oml1111 |
0 likes

A recursive implementation of the Extended Euclidean algorithm that runs in \(O(\log (a + b))\) time

Code

#include <tuple>

std::pair<int, int> extended_euclidean_algorithm(int a, int b) {
    if(b == 0) {
        return {1, 0};
    }
    std::pair<int, int> returned = extended_euclidean_algorithm(b, a%b);
    return {
        returned.second,
        returned.first - a/b * returned.second  // Integer division is by default towards zero
    };
}

int main() {
    int x, y;
    std::tie(x, y) = extended_euclidean_algorithm(173, 68);
    return 0;
}

References

functions
std::tie en.cppreference.com cplusplus.com
classes
std::pair en.cppreference.com cplusplus.com

Problem Description

Implement the Extended Euclidean Algorithm. Use it to find \(x\) and \(y\) satisfying the equation \(ax + by = \text{gcd}(a, b)\) for some values of \(a\) and \(b\).

Extended Euclidean algorithm - wikipedia.org

View sample discussion (0 comments)
View problem discussion (0 comments)