Algorithm/Baekjoon Online Judge

[Java] [Math] 백준 6064 카잉 달력 실버1

제우제우 2024. 5. 4. 16:40

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

import java.util.*;
import java.io.*;
public class Main {
    public static void main(String[] args) throws IOException{
        
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        int n = Integer.parseInt(br.readLine());
        
        while (n-->0){
            StringTokenizer st = new StringTokenizer(br.readLine());
            int N = Integer.parseInt(st.nextToken());
            int M = Integer.parseInt(st.nextToken());
            int x = Integer.parseInt(st.nextToken());
            int y = Integer.parseInt(st.nextToken());

            if(N == x) x = 0;
            if(M == y) y = 0;

            int max = 0;
            if(N >= M)  max = LCM(N , M);
            else max = LCM(M , N);

            if(x == 0 && y == 0){
                sb.append(max).append("\n");
                continue;
            }

            boolean flag = true;
            for (int i = x; i <= max; i+= N) {
                if(i % M == y){
                    sb.append(i).append("\n");
                    flag = false;
                    break;
                }
            }

            if(flag) sb.append("-1").append("\n");

        }
        System.out.println(sb);
    }
    
    public static int GCD(int a, int b){
        if(b == 0) return a;
        return GCD(b, a % b);
    
    public static int LCM(int a, int b){
        return a * b / GCD(a, b);
    }

}