[BOJ] 6064번 : 카잉 달력
2024. 9. 25. 08:35ㆍAlgorithm
1. problem :
https://www.acmicpc.net/problem/6064
2. solution 1 :
#include <bits/stdc++.h>
using namespace std;
int gcd(int a, int b) {
if (b == 0) return a;
return gcd(b, a % b);
}
int lcm(int a, int b) {
return a / gcd(a, b) * b;
}
int solve(int m, int n, int x, int y) {
if (x == m) x = 0;
if (y == n) y = 0;
int l = lcm(m, n);
for (int i = x; i <= l; i += m) {
if (i == 0) continue;
if (i % n == y) {
return i;
}
}
return -1;
}
int main(void) {
ios::sync_with_stdio(0);
cin.tie(0);
int t, m, n, x, y;
cin >> t;
while (t--) {
cin >> m >> n >> x >> y;
cout << solve(m, n, x, y) << '\n';
}
}
source code 출처 : https://github.com/encrypted-def/basic-algo-lecture/blob/master/0x12/solutions/6064.cpp
basic-algo-lecture/0x12/solutions/6064.cpp at master · encrypted-def/basic-algo-lecture
바킹독의 실전 알고리즘 강의 자료. Contribute to encrypted-def/basic-algo-lecture development by creating an account on GitHub.
github.com
이 문제는 최소공배수를 활용해서 , l을 지정한 다음, i % m == x를 만족시키는 값들로, i % n == y를 만족시키는 값들을 찾아가는 방식으로 구현되었다. i == 0일 때는 예외처리이다. 그 이유는 , i == 0일 때는 x == m이라는 것이고, 이때 y가 n이라면 y ==0이 된다. 따라서, return 값이 0이 되어, 잘못된 답을 출력할 수 있다. 따라서, i == 0일 때는 continue를 해준다고 한다. 아직 100% 이해는 못했고, 언젠가는 이해가 되기를 바란다.
'Algorithm' 카테고리의 다른 글
[BOJ] 11052번 : 카드 구매하기 (0) | 2024.09.26 |
---|---|
[BOJ] 2302번 : 극장 좌석 (0) | 2024.09.25 |
[BOJ] 11051번 : 이항 계수 2 (0) | 2024.09.25 |
[BOJ] 11050번 : 이항 계수 1 (0) | 2024.09.24 |
[BOJ] 15988번 : 1,2,3 더하기 3 (0) | 2024.09.23 |