Kaing Calendar
InterviewTime limit1sMemory limit256 MB
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 and that are at most and respectively, they wrote each year in the form .
The very first year of the world is written as and the second year as . If a given year is , the next year is determined as follows.
- If then ; otherwise .
- If then ; otherwise .
is the last year of this calendar, and legend says the world ends in that year.
For example, if and , then the 1st year is , the 11th year is , the 13th year is , and the last (60th) year is .
Given four integers , , , and , where is the last year of the Kaing calendar, write a program that determines which year represents.
Input
Input is given on standard input. The first line contains an integer , the number of test cases. Each of the following lines contains four integers , , , and . (, , ) Here denotes the last year of the Kaing calendar.
Output
For each test case, print on its own line the integer such that represents the -th year. If no year is represented by — that is, if is an invalid representation — print .