import sys
T = int(input())
for _ in range(T):
tmp = list(map(int, sys.stdin.readline()[:-1].split(' ')))
M = tmp[0]; N = tmp[1]; x = tmp[2]; y = tmp[3]
flag = 0
while(x <= M * N):
if x % N == y % N:
print(x)
flag = 1
break
x += M
if flag == 0:
print(-1)