Under construction

Still being built. Things may change

Rational Number Tree (Small)

Interview

Time limit5sMemory limit512 MB

Summary
Given the level-order listing of the rational number tree, find the n-th fraction and the position of a given fraction.
Level

Medium4 of 10

Topics
Tree, BFS, Hash map
Solved
No attempts yet

Problem

Consider an infinite complete binary tree whose root is 1/11/1, where the left child of the node p/qp/q is p/(p+q)p/(p+q) and the right child is (p+q)/q(p+q)/q. The top of the tree looks like this.

         1/1
    ______|______
    |           |
   1/2         2/1
 ___|___     ___|___
 |     |     |     |
1/3   3/2   2/3   3/1
...

Every positive rational number is known to appear in this tree exactly once. Traversing the tree in level order gives the following array.

1/1, 1/2, 2/1, 1/3, 3/2, 2/3, 3/1, ...

Answer the following two kinds of queries.

  1. Find the nn-th element of the array, counting from n=1n = 1. For example, if nn is 2, the answer is 1/21/2.
  2. Given a fraction p/qp/q in lowest terms, find its position in the array. For example, given 1/21/2, the answer is 2.

Input

The first line contains the number of test cases TT. The next TT lines each hold one test case. Each line contains a query id (1 or 2) and one or two integers.

  1. If the query id is 1, one integer nn follows, and you must find the nn-th element of the array.
  2. If the query id is 2, two integers pp and qq follow, and you must find the position of p/qp/q in the array.

Output

Print one line for each test case.

  1. If the query id is 1, print Case #x: p q, where x is the test case number starting from 1, and p and q are the numerator and the denominator of the requested element.
  2. If the query id is 2, print Case #x: n, where x is the test case number and n is the position of the given number.

Constraints

  • 1≤T≤1001 \le T \le 100
  • 1≤n,p,q≤216−11 \le n, p, q \le 2^{16} - 1
  • pp and qq are coprime.
  • p/qp/q sits at a node whose level number is at most 16. The root has level number 1.

Examples3

  1. Example 1

    Input
    4
    1 2
    2 1 2
    1 5
    2 3 2
    
    Expected output
    Case #1: 1 2
    Case #2: 2
    Case #3: 3 2
    Case #4: 5
    
  2. Example 2

    Input
    2
    1 1
    2 1 1
    
    Expected output
    Case #1: 1 1
    Case #2: 1
    
  3. Example 3

    Input
    7
    1 1
    1 2
    1 3
    1 4
    1 5
    1 6
    1 7
    
    Expected output
    Case #1: 1 1
    Case #2: 1 2
    Case #3: 2 1
    Case #4: 1 3
    Case #5: 3 2
    Case #6: 2 3
    Case #7: 3 1