The Sorting Hat

No attempts yetTime limit1sMemory limit256 MB

Problem

A school of magic has always sorted its students into departments with an enchanted hat. The school used to have 4 departments, but after a reorganization it has pp of them. The hat still does the sorting.

A sorting plan is a sequence a[1],a[2],,a[k]a[1], a[2], \dots, a[k], where a[i]a[i] is the department that student ii joins.

The hat builds a plan like this. The departments are numbered from 00 to p1p-1. Write next(x)\text{next}(x) for the department after xx, so next(x)=x+1\text{next}(x) = x+1 when x<p1x < p-1 and next(p1)=0\text{next}(p-1) = 0. The plan starts as a sequence with the single element 00. After each step, a sequence aa with kk elements becomes the sequence a[1],a[2],,a[k],next(a[1]),next(a[2]),,next(a[k])a[1], a[2], \dots, a[k], \text{next}(a[1]), \text{next}(a[2]), \dots, \text{next}(a[k]) with 2k2k elements.

Here is how 9 students are sorted into 4 departments. The hat grows the plan in this order:

(0)(0,1)(0,1,1,2)(0,1,1,2,1,2,2,3)(0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,0)(0) \to (0, 1) \to (0, 1, 1, 2) \to (0, 1, 1, 2, 1, 2, 2, 3) \to (0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 0)

The last sequence is long enough for 9 students. Repeating the step makes the sequence as long as you like, so every student number gets a department.

You are given several pairs nn and pp. For each pair, report the department that student nn joins when the school has pp departments. Students are numbered from 1.

Input

The first line contains the number of queries QQ (1Q3100001 \le Q \le 310\,000).

Each of the next QQ lines contains two integers nn and pp in that order, separated by a space (1n10181 \le n \le 10^{18}, 2p10182 \le p \le 10^{18}).

Output

Print QQ lines, one answer per query, in the order the queries are given. Each line holds the number of the department that student nn joins.