sotanishy's code snippets for competitive programming
#include "math/number-theory/extgcd.hpp"
拡張 Euclid の互除法は,2変数1次不定方程式 $ax + by = \gcd(a, b)$ の解 $(x, y)$ を1組求めるアルゴリズムである.
また,これを利用して,与えられた整数 $a$ の法 $mod$ での逆元を求めることができる.Fermat の小定理を利用したアルゴリズムより制約が少なく定数倍高速であるため,基本的にこちらを用いる.
pair<long long, long long> extgcd(long long a, long long b)
long long mod_inv(long long a, long long mod)
#pragma once
#include <algorithm>
#include <utility>
std::pair<long long, long long> extgcd(long long a, long long b) {
long long s = a, sx = 1, sy = 0, t = b, tx = 0, ty = 1;
while (t) {
long long q = s / t;
std::swap(s -= t * q, t);
std::swap(sx -= tx * q, tx);
std::swap(sy -= ty * q, ty);
}
return {sx, sy};
}
long long mod_inv(long long a, long long mod) {
long long inv = extgcd(a, mod).first;
return (inv % mod + mod) % mod;
}
#line 2 "math/number-theory/extgcd.hpp"
#include <algorithm>
#include <utility>
std::pair<long long, long long> extgcd(long long a, long long b) {
long long s = a, sx = 1, sy = 0, t = b, tx = 0, ty = 1;
while (t) {
long long q = s / t;
std::swap(s -= t * q, t);
std::swap(sx -= tx * q, tx);
std::swap(sy -= ty * q, ty);
}
return {sx, sy};
}
long long mod_inv(long long a, long long mod) {
long long inv = extgcd(a, mod).first;
return (inv % mod + mod) % mod;
}