RealPhobia
InterviewTime limit1sMemory limit128 MB
For each fraction A/B, find C/D with D < B that minimizes the error |A/B - C/D|, breaking ties by the smallest denominator.
- Level
Medium7 of 10
- Topics
- Number theory, Math, Binary search, Brute force
- Solved
- No attempts yet
Problem
Bert is a programmer who is genuinely afraid of floating-point arithmetic. He has had great success writing his programs with rational numbers instead, but he dislikes it when a denominator grows large.
Help Bert by writing a program that lowers the denominator of a rational number while introducing the smallest possible error. For a rational number with and , find a rational number such that:
- ;
- the error is the minimum over all valid and ; and
- among all pairs achieving that minimum error, is the smallest possible positive integer.
Because condition 3 minimises , the answer fraction is always already in lowest terms.
Input
The first line contains an integer (), the number of test cases. Each of the next lines contains one test case: a fraction written as two integers and separated by a slash (/), where
- is a 32-bit integer strictly greater than , and
- .
Output
For each test case, print one line containing the fraction , written as two integers separated by a slash (/).