serna37's Library

Logo

C++ アルゴリズムとデータ構造のライブラリ

View the Project on GitHub serna37/library-cpp

:heavy_check_mark: 拡張Euclidの互除法
(library/number/ext_gcd.hpp)

拡張Euclidの互除法

できること

計算量

$O(\log \min(a, b))$

使い方

int a, b, x, y;
cin >> a >> b;
ext_gcd(a, b, x, y);

Verified with

Code

#pragma once
template <typename T> T ext_gcd(T a, T b, T &x, T &y) {
    T d = a;
    if (b != 0ll) {
        d = ext_gcd(b, a % b, y, x);
        y -= (a / b) * x;
    } else {
        x = 1ll;
        y = 0ll;
    }
    return d;
}
#line 2 "library/number/ext_gcd.hpp"
template <typename T> T ext_gcd(T a, T b, T &x, T &y) {
    T d = a;
    if (b != 0ll) {
        d = ext_gcd(b, a % b, y, x);
        y -= (a / b) * x;
    } else {
        x = 1ll;
        y = 0ll;
    }
    return d;
}
Back to top page