Algorithms

This documentation is automatically generated by online-judge-tools/verification-helper

View the Project on GitHub HyunjaeLee/Algorithms

:heavy_check_mark: Extended Euclidean Algorithm
(math/extgcd.hpp)

Computes $g = \gcd(a,b)$ and find integers $x$ and $y$ such that $ax+by=g$.

Bézout’s identity—Let $a$ and $b$ be integers with greatest common divisor $g$. Then there exist integers $x$ and $y$ such that $ax + by = g$. Moreover, the integers of the form $az + bt$ are exactly the multiples of $g$.

Complexity

References

Verified with

Code

#ifndef EXTGCD_HPP
#define EXTGCD_HPP

template <typename T> T extgcd(T a, T b, T &x, T &y) {
    if (b == 0) {
        x = 1, y = 0;
        return a;
    }
    T d = extgcd(b, a % b, y, x);
    y -= a / b * x;
    return d;
}

#endif // EXTGCD_HPP
#line 1 "math/extgcd.hpp"



template <typename T> T extgcd(T a, T b, T &x, T &y) {
    if (b == 0) {
        x = 1, y = 0;
        return a;
    }
    T d = extgcd(b, a % b, y, x);
    y -= a / b * x;
    return d;
}
Back to top page