CF2180A.Carnival Wheel

传统题 时间 2000 ms 内存 256 MiB 3 尝试 1 已通过 1 标签

Carnival Wheel

You have a prize wheel divided into ll sections, numbered from 00 to l1l-1. The sections are arranged in a circle, so after section l1l-1, the numbering continues again from section 00.

Initially, the prize pointer is at section aa. Each time you spin the wheel, the pointer moves exactly bb sections forward. That is, after one spin, the pointer moves from section aa to section (a+b)modl(a+b)\bmod l, after two spins to (a+2b)modl(a+2b)\bmod l, and so on^{\text{∗}}.

You may spin the wheel any number of times (including zero). After you stop, the section where the pointer finally lands determines your prize: you receive an amount equal to the number of that section.

What is the maximum prize you can obtain?

^{\text{∗}}Here, xmodyx \bmod y denotes the remainder from dividing xx by yy.

Input

Each test contains multiple test cases. The first line contains the number of test cases tt (1t5001 \le t \le 500). The description of the test cases follows.

The first line of each test case contains three integers l,al, a, and bb (1l,b50001 \le l, b \le 5000, 0al10 \le a \le l-1).

Output

For each test case, output the maximum prize that can be obtained.

Note

In the first test case, by spinning the wheel three times and then claiming the reward, you can obtain a maximum value of 44. The sequence of pointer positions is: 3,0,2,4,1,3,0,3, 0, 2, 4, 1, 3, 0, \ldots

In the second test case, the pointer will remain on section 00 indefinitely.

In the fourth test case, with b=1b = 1 and starting from section 00, the pointer will iterate over all sections, including the last one.

Link to the visualizer

Samples

4
5 3 2
2 0 6
8 2 4
100 0 1
4
0
6
99

在线编程 IDE

建议全屏模式获得最佳体验