This page is still under construction.

Parts of this page are still being built. What you see may change.

A Rational Sequence

Time limit1sMemory limit256 MB

Summary
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 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 (1≤P≤10001 \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.

Examples2

  1. Example 1

    Input
    4
    1 1/1
    2 1/3
    3 5/2
    4 2178309/1346269
    
    Expected output
    1 1
    2 4
    3 11
    4 1431655765
    
  2. Example 2

    Input
    15
    1 1/1
    2 1/2
    3 2/1
    4 1/3
    5 3/2
    6 2/3
    7 3/1
    8 1/4
    9 4/3
    10 3/5
    11 5/2
    12 2/5
    13 5/3
    14 3/4
    15 4/1
    
    Expected output
    1 1
    2 2
    3 3
    4 4
    5 5
    6 6
    7 7
    8 8
    9 9
    10 10
    11 11
    12 12
    13 13
    14 14
    15 15