This page is still under construction.

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

Rational Sequence

Interview

Time limit2sMemory limit512 MB

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

Examples2

  1. Example 1

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

    Input
    1
    1/1
    
    Expected output
    1