Rational Number Tree (Small)
InterviewTime limit5sMemory limit512 MB
Given the level-order listing of the rational number tree, find the n-th fraction and the position of a given fraction.
Problem
Consider an infinite complete binary tree whose root is , where the left child of the node is and the right child is . The top of the tree looks like this.
1/1
______|______
| |
1/2 2/1
___|___ ___|___
| | | |
1/3 3/2 2/3 3/1
...
Every positive rational number is known to appear in this tree exactly once. Traversing the tree in level order gives the following array.
1/1, 1/2, 2/1, 1/3, 3/2, 2/3, 3/1, ...
Answer the following two kinds of queries.
- Find the -th element of the array, counting from . For example, if is 2, the answer is .
- Given a fraction in lowest terms, find its position in the array. For example, given , the answer is 2.
Input
The first line contains the number of test cases . The next lines each hold one test case. Each line contains a query id (1 or 2) and one or two integers.
- If the query id is 1, one integer follows, and you must find the -th element of the array.
- If the query id is 2, two integers and follow, and you must find the position of in the array.
Output
Print one line for each test case.
- If the query id is 1, print
Case #x: p q, wherexis the test case number starting from 1, andpandqare the numerator and the denominator of the requested element. - If the query id is 2, print
Case #x: n, wherexis the test case number andnis the position of the given number.
Constraints
- and are coprime.
- sits at a node whose level number is at most 16. The root has level number 1.