#P16470. [GKS 2013 #A] Rational Number Tree

[GKS 2013 #A] Rational Number Tree

Problem Description

Consider an infinite complete binary tree where the root node is 1/11/1 and left and right childs of node p/qp/q are p/(p+q)p/(p+q) and (p+q)/q(p+q)/q, respectively. This tree looks like:

:::align{center} :::

It is known that every positive rational number appears exactly once in this tree. A level-order traversal of the tree results in the following array:

1/11/1, 1/21/2, 2/12/1, 1/31/3, 3/23/2, 2/32/3, 3/13/1, \dots

Please solve the following two questions:

  1. Find the nn-th element of the array, where nn starts from 11. For example, for the input 22, the correct output is 1/21/2.
  2. Given p/qp/q, find its position in the array. As an example, the input 1/21/2 results in the output 22.

Input Format

The first line of the input gives the number of test cases, TT. TT test cases follow. Each test case consists of one line. The line contains a problem id (11 or 22) and one or two additional integers:

  1. If the problem id is 11, then only one integer nn is given, and you are expected to find the nn-th element of the array.
  2. If the problem id is 22, then two integers pp and qq are given, and you are expected to find the position of p/qp/q in the array.

Output Format

For each test case:

  1. If the problem id is 11, then output one line containing "Case #x: p q", where xx is the case number (starting from 11), and p,qp, q are numerator and denominator of the asked array element, respectively.
  2. If the problem id is 22, then output one line containing "Case #x: n", where xx is the case number (starting from 11), and nn is the position of the given number.
4
1 2
2 1 2
1 5
2 3 2
Case #1: 1 2
Case #2: 2
Case #3: 3 2
Case #4: 5

Hint

Limits

1T1001 \le T \le 100; pp and qq are relatively prime.

Test set 1 - Visible

1n,p,q21611 \le n, p, q \le 2^{16}-1; p/qp/q is an element in a tree with level number 16\le 16.

Test set 2 - Hidden

1n,p,q26411 \le n, p, q \le 2^{64}-1; p/qp/q is an element in a tree with level number 64\le 64.