Min-cost GCD
Time limit1sMemory limit32 MB
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.
- Level
Medium7 of 10
- Topics
- Greedy, Number theory, Math
- Solved
- No attempts yet
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 and turns it into . One request costs won.
- Sangsu takes a pair and turns it into if , or into if . One request costs won.
For example:
- becomes with Seokhwan and with Sangsu.
- becomes with Seokhwan and with Sangsu.
- becomes with Seokhwan and with Sangsu.
Seunghyun has an ordered pair of natural numbers . 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 . At that point is the greatest common divisor of the two numbers he started with.
Seunghyun then wondered what the smallest cost of reaching is once , , , and 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 .
Each of the next lines contains one test case. Line contains four natural numbers , , , separated by spaces.
- for every
- 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 , pays won for one request to Seokhwan and won for one request to Sangsu, and has to reach using processing requests only.
Hint
When is , , or , using Seokhwan alone is optimal.
When it is , 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 won.