Notice
Recent Posts
Recent Comments
Link
«   2026/06   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
Archives
Today
Total
관리 메뉴

dh-winternagi 님의 블로그

(14565) 역원(Inverse) 구하기 본문

백준 (C++)/Solve

(14565) 역원(Inverse) 구하기

dh-winternagi 2026. 4. 24. 13:46

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

단계별로 풀어보기

45단계(수학 2) 2번째

 

 

 

덧셈역은 n-a라는 것을 아주 쉽게 알 수 있다.

ax+my=1에서 ax ≡ 1-my ≡ 1 (mod m)이므로 확장 유클리드 알고리즘으로 구한 x값이 a의 곱셈역이다.

a와 m이 서로소가 아니라면 역원은 없고, 구한 x값이 음수일수도 있으므로 Zn 내 범위로 변경해준다.

 

 

 

#include <iostream>
using namespace std;

int main() {
  long n, a;
  
  cin >> n >> a;
  
  cout << n-a << " ";
  
  long q;
  pair<long, long> r= {a, n};
  pair<long, long> s= {1, 0};
  pair<long, long> t= {0, 1};
  
  while(r.second){
    q= r.first/r.second;
    r= {r.second, r.first-r.second*q};
    s= {s.second, s.first-s.second*q};
    t= {t.second, t.first-t.second*q};
  }
  
  if(abs(r.first)!=1)  cout << -1;
  else  cout << (s.first>0 ? s.first : s.first+n);
  
  return 0;
}

'백준 (C++) > Solve' 카테고리의 다른 글

(13977) 이항 계수와 쿼리  (0) 2026.04.24
(20412) 추첨상 사수 대작전! (Hard)  (0) 2026.04.24
(3955) 캔디 분배  (0) 2026.04.24
(1168) 요세푸스 문제 2  (0) 2026.04.24
(12899) 데이터 구조  (0) 2026.04.24