Under construction

Still being built. Things may change

Maximum Sine

Time limit3sMemory limit1024 MB

Summary
Given a, b, p, and q, find the smallest integer x in [a, b] that maximizes |sin(p/q * pi * x)| across multiple test cases.
Level

Medium7 of 10

Topics
Math, Number theory
Solved
No attempts yet

Problem

You are given integers aa, bb, pp, and qq. Let f(x)=∣sin⁡(pqπx)∣f(x) = |\sin(\frac{p}{q} \pi x)|. Find the minimum integer xx that maximizes f(x)f(x) over all integers xx with a≤x≤ba \le x \le b.

Input

The first line contains the number of test cases tt (1≤t≤1001 \le t \le 100). Each test case is on its own line and contains four integers aa, bb, pp, and qq (0≤a≤b≤1090 \le a \le b \le 10^{9}, 1≤p,q≤1091 \le p, q \le 10^{9}).

Output

For each test case, print the minimum integer xx that maximizes f(x)f(x), one per line.

Hint

In the first test case, f(0)=0f(0) = 0, f(1)=f(2)≈0.866f(1) = f(2) \approx 0.866, and f(3)=0f(3) = 0. In the second test case, f(55)≈0.999969f(55) \approx 0.999969, which is the largest value among all candidates.

Examples1

  1. Example 1

    Input
    2
    0 3 1 3
    17 86 389 995
    
    Expected output
    1
    55