count = int(input())
case = []
for q in range(count):
    case.append(input())


def sol(n):
    M, N, x, y = map(int, n.split())
    answer = x
    while (answer - y) % N != 0 and answer <= M * N:
        answer += M
    print(-(answer > M * N) or answer)


if __name__ == '__main__':
    for i in case:
        sol(i)

d269132ebb3acb9c014970f433ed43c87dc85646
<mask token>

<mask token>


def sol(n):
    M, N, x, y = map(int, n.split())
    answer = x
    while (answer - y) % N != 0 and answer <= M * N:
        answer += M
    print(-(answer > M * N) or answer)


<mask token>

<mask token>
for q in range(count):
    case.append(input())


def sol(n):
    M, N, x, y = map(int, n.split())
    answer = x
    while (answer - y) % N != 0 and answer <= M * N:
        answer += M
    print(-(answer > M * N) or answer)


if __name__ == '__main__':
    for i in case:
        sol(i)

count = int(input())
case = []
for q in range(count):
    case.append(input())


def sol(n):
    M, N, x, y = map(int, n.split())
    answer = x
    while (answer - y) % N != 0 and answer <= M * N:
        answer += M
    print(-(answer > M * N) or answer)


if __name__ == '__main__':
    for i in case:
        sol(i)
