알고리즘
6064_카잉 달력
shj718
2023. 1. 5. 15:56
주기 M을 이용해서 후보 년도를 만든 다음, 주기 N에 대한 조건도 만족하는지 검사했다. (처음에 1번째 해부터 1씩 증가시키면서 M, N 조건을 검사하는 방식으로 풀었더니 시간초과가 떠서 이렇게 수정했다.)
마지막 해는 x, y의 최소공배수이다. 최소공배수는 '두 수의 곱 / 최대공약수' 이다. 최대공약수는 유클리드 호제법을 이용해서 구한다.
y == n 인 경우에 대한 예외 처리도 해주었다.
#include <iostream>
using namespace std;
int get_gcd(int a, int b) {
int c;
while (b)
{
c = a % b;
a = b;
b = c;
}
return a;
}
int get_lcm(int a, int b) {
int gcd = get_gcd(a, b);
return a * b / gcd;
}
int main() {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int t;
int m, n, x, y;
cin >> t;
while (t--) {
cin >> m >> n >> x >> y;
int lastYear = get_lcm(m, n);
int k = -1;
int i = 0, tmp;
while (1) {
tmp = m * i + x;
if (tmp > lastYear) break;
if ((tmp - 1) % n + 1 == y) {
k = tmp;
}
i++;
}
cout << k << '\n';
}
return 0;
}