import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class BOJ_6064 {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(br.readLine());
while (t-- > 0) {
String[] line = br.readLine().split("\\s");
int m = Integer.parseInt(line[0]);
int n = Integer.parseInt(line[1]);
int x = Integer.parseInt(line[2]);
int y = Integer.parseInt(line[3]);
int tempX = x;
int tempY = x;
boolean ok = false;
while (tempY <= m * n) {
// 1. y != n
// 2. y == n
if ((tempY % n) == y || (tempY % n) == 0 && y % n == 0) {
System.out.println(tempY);
ok = true;
break;
}
tempY += m;
}
if (!ok)
System.out.println(-1);
}
}
}