This page is still under construction.

Parts of this page are still being built. What you see may change.

Kaing Calendar

Interview

Time limit1sMemory limit256 MB

Summary
Given cycle lengths M and N, find the smallest k with k mod M = x and k mod N = y, the CRT problem, or report -1.
Level

Medium6 of 10

Topics
Math, Number theory, Brute force, Implementation
Solved
No attempts yet

Problem

An archaeological expedition recently discovered that the Inca Empire of South America was founded upon the Kaing Empire, a civilization of remarkable achievement. The people of the Kaing Empire are known to have used an unusual calendar. Using two natural numbers xx and yy that are at most MM and NN respectively, they wrote each year in the form ⟨x:y⟩\langle x{:}y \rangle.

The very first year of the world is written as ⟨1:1⟩\langle 1{:}1 \rangle and the second year as ⟨2:2⟩\langle 2{:}2 \rangle. If a given year is ⟨x:y⟩\langle x{:}y \rangle, the next year ⟨x′:y′⟩\langle x'{:}y' \rangle is determined as follows.

  • If x<Mx < M then x′=x+1x' = x + 1; otherwise x′=1x' = 1.
  • If y<Ny < N then y′=y+1y' = y + 1; otherwise y′=1y' = 1.

⟨M:N⟩\langle M{:}N \rangle is the last year of this calendar, and legend says the world ends in that year.

For example, if M=10M = 10 and N=12N = 12, then the 1st year is ⟨1:1⟩\langle 1{:}1 \rangle, the 11th year is ⟨1:11⟩\langle 1{:}11 \rangle, the 13th year is ⟨3:1⟩\langle 3{:}1 \rangle, and the last (60th) year is ⟨10:12⟩\langle 10{:}12 \rangle.

Given four integers MM, NN, xx, and yy, where ⟨M:N⟩\langle M{:}N \rangle is the last year of the Kaing calendar, write a program that determines which year ⟨x:y⟩\langle x{:}y \rangle represents.

Input

Input is given on standard input. The first line contains an integer TT, the number of test cases. Each of the following lines contains four integers MM, NN, xx, and yy. (1≤M,N≤40,0001 \le M, N \le 40{,}000, 1≤x≤M1 \le x \le M, 1≤y≤N1 \le y \le N) Here ⟨M:N⟩\langle M{:}N \rangle denotes the last year of the Kaing calendar.

Output

For each test case, print on its own line the integer kk such that ⟨x:y⟩\langle x{:}y \rangle represents the kk-th year. If no year is represented by ⟨x:y⟩\langle x{:}y \rangle — that is, if ⟨x:y⟩\langle x{:}y \rangle is an invalid representation — print −1-1.

Examples3

  1. Example 1

    Input
    3
    10 12 3 9
    10 12 7 2
    13 11 5 6
    
    Expected output
    33
    -1
    83
    
  2. Example 2

    Input
    1
    1 1 1 1
    
    Expected output
    1
    
  3. Example 3

    Input
    1
    6 4 3 1
    
    Expected output
    9