Min-cost GCD

Pay q per subtraction step and p per modulo step to reduce the pair (a, b) until one entry is zero, and report the cheapest total cost.

Medium7GreedyNumber theoryMathNo attempts yetTime limit1sMemory limit32 MB

Problem

Computing the greatest common divisor of two natural numbers comes up often. In this problem you compute it at a smaller cost.

Seokhwan and Sangsu are natural number processors. A customer hands them one ordered pair of natural numbers, and they process the pair and hand it back.

  • Seokhwan takes a pair (x,y)(x, y) and turns it into (y,xmody)(y, x \bmod y). One request costs pp won.
  • Sangsu takes a pair (x,y)(x, y) and turns it into (xy,y)(x - y, y) if xyx \ge y, or into (x,yx)(x, y - x) if x<yx < y. One request costs qq won.

For example:

  • (21,5)(21, 5) becomes (5,1)(5, 1) with Seokhwan and (16,5)(16, 5) with Sangsu.
  • (5,21)(5, 21) becomes (21,5)(21, 5) with Seokhwan and (5,16)(5, 16) with Sangsu.
  • (15,21)(15, 21) becomes (21,15)(21, 15) with Seokhwan and (15,6)(15, 6) with Sangsu.

Seunghyun has an ordered pair of natural numbers (a,b)(a, b). He is good at mathematics, and he worked out that sending the pair to Seokhwan and Sangsu in a suitable order eventually reaches a pair with ab=0ab = 0. At that point a+ba + b is the greatest common divisor of the two numbers he started with.

Seunghyun then wondered what the smallest cost of reaching ab=0ab = 0 is once aa, bb, pp, and qq are fixed. He cannot change the numbers himself, so he can only request processing. Compute that smallest cost for him.

Input

The first line contains the number of test cases TT.

Each of the next TT lines contains one test case. Line ii (1iT)(1 \le i \le T) contains four natural numbers aia_i, bib_i, pip_i, qiq_i separated by spaces.

  • 1T1000001 \le T \le 100000
  • 1ai,bi,pi,qi10151 \le a_i, b_i, p_i, q_i \le 10^{15} for every ii (1iT)(1 \le i \le T)
  • Every number in the input is a natural number.

Output

For each test case, print the smallest cost in won on its own line. Seunghyun starts from the pair (ai,bi)(a_i, b_i), pays pip_i won for one request to Seokhwan and qiq_i won for one request to Sangsu, and has to reach aibi=0a_i b_i = 0 using processing requests only.

Hint

When (a,b,p,q)(a, b, p, q) is (7,3,1,1)(7, 3, 1, 1), (8,3,1,1)(8, 3, 1, 1), or (7,3,3,2)(7, 3, 3, 2), using Seokhwan alone is optimal.

When it is (55,34,10,9)(55, 34, 10, 9), both of them are needed. In the path below, --q--> is a request to Sangsu and --p--> is a request to Seokhwan.

(55, 34) --q--> (21, 34) --q--> (21, 13) --q--> (8, 13) --q--> (8, 5)
(8, 5) --p--> (5, 3) --q--> (2, 3) --q--> (2, 1) --p--> (1, 0)

Six requests to Sangsu and two to Seokhwan cost 6×9+2×10=746 \times 9 + 2 \times 10 = 74 won.