A Rational Sequence

Given a reduced fraction p/q from the Calkin-Wilf tree, compute its position n in breadth-first order.

Medium5MathTreeBit manipulationNo attempts yetTime limit1sMemory limit256 MB

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 1/11/1.
  • The left child of a node labeled p/qp/q is labeled p/(p+q)p/(p+q).
  • The right child of a node labeled p/qp/q is labeled (p+q)/q(p+q)/q.

The top of the tree looks like this:

The sequence FF comes from a level order (breadth first) traversal of the tree, drawn as the light dashed line in the figure. That gives F(1)=1/1F(1) = 1/1, F(2)=1/2F(2) = 1/2, F(3)=2/1F(3) = 2/1, F(4)=1/3F(4) = 1/3, F(5)=3/2F(5) = 3/2, F(6)=2/3F(6) = 2/3, and so on.

Given pp and qq, find the value of nn for which F(n)=p/qF(n) = p/q.

Input

The first line contains one integer PP, the number of data sets (1P10001 \le P \le 1000). Each data set is independent of the others and is processed the same way.

Each of the next PP lines holds one data set: the data set number KK, a single space, the numerator pp, a forward slash (/), and the denominator qq. 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 KK, a single space, and the value of nn for which F(n)=p/qF(n) = p/q. The inputs are chosen so that nn fits in a signed 32-bit integer.