A Rational Sequence
Time limit1sMemory limit256 MB
Given a reduced fraction p/q from the Calkin-Wilf tree, compute its position n in breadth-first order.
- Level
Medium5 of 10
- Topics
- Math, Tree, Bit manipulation
- Solved
- No attempts yet
Problem
A sequence of positive rational numbers comes from an infinite complete binary tree whose nodes are labeled by positive rationals.
- The root is labeled .
- The left child of a node labeled is labeled .
- The right child of a node labeled is labeled .
The top of the tree looks like this:

The sequence comes from a level order (breadth first) traversal of the tree, drawn as the light dashed line in the figure. That gives , , , , , , and so on.
Given and , find the value of for which .
Input
The first line contains one integer , the number of data sets (). Each data set is independent of the others and is processed the same way.
Each of the next lines holds one data set: the data set number , a single space, the numerator , a forward slash (/), and the denominator . Every fraction given is in lowest terms, so it appears exactly once in the tree.
Output
Print one line per data set: the data set number , a single space, and the value of for which . The inputs are chosen so that fits in a signed 32-bit integer.