Rational Sequence

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.

Medium4MathNumber theoryTreeImplementationInterviewNo attempts yetTime limit2sMemory limit512 MB

Problem

Label the nodes of an infinite rooted binary tree with rational numbers by the following rule.

  • The root is labeled 1/11/1.
  • If a node is labeled p/qp/q, then its left child is labeled p/(p+q)p/(p+q) and its right child is labeled (p+q)/q(p+q)/q.

Traverse this tree in breadth first order, visiting the nodes of the same depth from left to right, and read off the rational sequence a1,a2,a3,a_1, a_2, a_3, \dots. This gives a1=1/1a_1 = 1/1, a2=1/2a_2 = 1/2, a3=2/1a_3 = 2/1, a4=1/3a_4 = 1/3, a5=3/2a_5 = 3/2.

Given pp and qq, write a program that computes the integer nn with an=p/qa_n = p/q.

Input

The first line contains the number of test cases tt (1t10001 \le t \le 1000).

Each of the next tt lines holds one test case: pp, the character /, and qq, written with no spaces between them. Every given p/qp/q appears in the tree, and in every test case the answer nn fits in a 32-bit integer.

Output

For each test case, print on its own line the integer nn with an=p/qa_n = p/q.