Skip to content

Commit 45118a1

Browse files
committed
docs: 모듈러 역원 예제 추가
1 parent 3196fb6 commit 45118a1

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

_posts/2024-03-06-modular-arithmetic.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -154,6 +154,48 @@ console.log(modInverse(3, 11)); // 4
154154
}
155155
```
156156

157+
- <a href="https://www.acmicpc.net/problem/14565" target="_blank">14565번: 역원(Inverse) 구하기</a>
158+
159+
```javascript
160+
const path = process.platform === "linux" ? "/dev/stdin" : "input.txt";
161+
const input = require("fs").readFileSync(path).toString();
162+
163+
// 2 <= N <= 10^12
164+
// 1 <= A < N
165+
const [N, A] = input.split(" ").map(Number);
166+
167+
const gcd = (a, b) => {
168+
if (b === 0) {
169+
return a;
170+
} else {
171+
return gcd(b, a % b);
172+
}
173+
};
174+
175+
const modInverse = (a, m) => {
176+
if (m === 1) {
177+
return 0;
178+
}
179+
180+
const m0 = m;
181+
let x0 = 0;
182+
let x1 = 1;
183+
184+
while (a > 1) {
185+
const q = Math.floor(a / m);
186+
[a, m] = [m, a % m];
187+
[x0, x1] = [x1 - q * x0, x0];
188+
}
189+
190+
if (x1 < 0) {
191+
x1 += m0;
192+
}
193+
return x1;
194+
};
195+
196+
console.log(N - A, gcd(A, N) === 1 ? modInverse(A, N) : -1);
197+
```
198+
157199
## 참고 자료
158200

159201
- <a href="https://ko.wikipedia.org/wiki/모듈러_산술" target="_blank">모듈러 산술 - 위키백과, 우리 모두의 백과사전</a>

0 commit comments

Comments
 (0)