cpplib

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

View the Project on GitHub morioprog/cpplib

:heavy_check_mark: 拡張ユークリッドの互除法
(math/extgcd.hpp)

概要

与えられた$a, b$に対して, 最大公約数$gcd(a, b)$と, $ax + by = gcd(a, b)$なる$x, y$を求める.

計算量

$O(\log a)$

使用例

Verified with

Code

/**
* @brief 拡張ユークリッドの互除法
* @docs docs/math/extgcd.md
*/

long long extgcd(long long a, long long b, long long &x, long long &y) {
    if (b == 0) {
        x = 1;
        y = 0;
        return a;
    }
    long long d = extgcd(b, a % b, y, x);
    y -= a / b * x;
    return d;
}
#line 1 "math/extgcd.hpp"
/**
* @brief 拡張ユークリッドの互除法
* @docs docs/math/extgcd.md
*/

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