Rational Sequence
InterviewTime limit2sMemory limit512 MB
Given p/q, find its index in the breadth-first ordering of the Calkin-Wilf tree, where each node p/q has children p/(p+q) and (p+q)/q.
- Level
Medium4 of 10
- Topics
- Math, Number theory, Tree, Implementation
- Solved
- No attempts yet
Problem
Label the nodes of an infinite rooted binary tree with rational numbers by the following rule.
- The root is labeled .
- If a node is labeled , then its left child is labeled and its right child is labeled .

Traverse this tree in breadth first order, visiting the nodes of the same depth from left to right, and read off the rational sequence . This gives , , , , .
Given and , write a program that computes the integer with .
Input
The first line contains the number of test cases ().
Each of the next lines holds one test case: , the character /, and , written with no spaces between them. Every given appears in the tree, and in every test case the answer fits in a 32-bit integer.
Output
For each test case, print on its own line the integer with .