백준 알고리즘 14565번 : 역원(Inverse) 구하기

Zoo Da·2021년 11월 7일
0

백준 알고리즘

목록 보기
247/337
post-thumbnail

링크

https://www.acmicpc.net/problem/14565

sol1) 확장된 유클리드 호제법

#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#include<bits/stdc++.h>
#define X first
#define Y second
#define pb push_back
#define fastio cin.tie(0)->sync_with_stdio(0)
#define sz(v) (int)(v).size()
#define all(v) v.begin(), v.end()
#define rall(v) (v).rbegin(), (v).rend()
#define compress(v) sort(all(v)), (v).erase(unique(all(v)), (v).end())
#define OOB(x, y) ((x) < 0 || (x) >= n || (y) < 0 || (y) >= m)
#define debug(x) cout << (#x) << ": " << (x) << '\n'
using namespace std;
using ll = long long;
using ull = unsigned long long;
using dbl = double;
using ldb = long double;
using pii = pair<int,int>;
using pll = pair<ll,ll>;
using vi = vector<int>;
using vs = vector<string>;
using tii = tuple<int,int,int>;
template<typename T> using wector = vector<vector<T>>;

const int MOD = 1e9 + 7;
const int INF = 1e9 + 7;
const ll LNF = 1e18 + 7;

namespace number_theory{
	ll gcd(ll x, ll y) { return y ? gcd(y, x%y) : x; }
	ll mod(ll a, ll b) { return ((a%b) + b) % b; }

	// returns g = gcd(a, b); finds x, y such that d = ax + by
	ll ext_gcd(ll a, ll b, ll &x, ll &y) {
		ll xx = y = 0;
		ll yy = x = 1;
		while (b) {
			ll q = a / b;
			ll t = b; b = a%b; a = t;
			t = xx; xx = x - q*xx; x = t;
			t = yy; yy = y - q*yy; y = t;
		}
		return a;
	}

	// computes b such that ab = 1 (mod n), returns -1 on failure
	ll mod_inverse(ll a, ll n) {
		ll x, y;
		ll g = ext_gcd(a, n, x, y);
		if (g > 1) return -1;
		return mod(x, n);
	}

	// Chinese remainder theorem: find z such that
	// z % m1 = r1, z % m2 = r2.  Here, z is unique modulo M = lcm(m1, m2).
	// Return (z, M).  On failure, M = -1.
	pair<ll, ll> CRT(ll m1, ll r1, ll m2, ll r2) {
		ll s, t;
		ll g = ext_gcd(m1, m2, s, t);
		if (r1%g != r2%g) return make_pair(0, -1);
		return make_pair(mod(s*r2*m1 + t*r1*m2, m1*m2) / g, m1*m2 / g);
	}
}

int main() {
  fastio;
  ll n,a; cin >> n >> a;
  cout << n - a << ' ' << number_theory::mod_inverse(a, n) << "\n";
  return 0;
}

구현에는 koosaga님의 소스코드를 참고하였습니다.

profile
메모장 겸 블로그

0개의 댓글