Repository navigation
Expand file tree
/
Copy pathKayingCal.java
More file actions
52 lines (44 loc) · 1.42 KB
/
Copy pathKayingCal.java
File metadata and controls
52 lines (44 loc) · 1.42 KB
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.*;
class KayingCal {
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
StringTokenizer st;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < t; i++) {
st = new StringTokenizer(br.readLine());
int M = Integer.parseInt(st.nextToken());
int N = Integer.parseInt(st.nextToken());
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
int cnt = x % (M + 1);
int tempy = x;
for (int j = 0; j < N; j++) {
int ty = tempy % N == 0 ? N : tempy % N;
if(ty == y) {
break;
}
tempy = ty + M;
cnt += M;
}
sb.append(cnt > lcm(M, N) ? "-1" : cnt);
sb.append("\n");
}
System.out.println(sb.toString());
}
public static int gcd(int a, int b) {
while (b != 0) {
int r = a % b;
a = b;
b = r;
}
return a;
}
public static int lcm(int a, int b) {
return a * b / gcd(a, b);
}
}