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 p of them. The hat still does the sorting.
A sorting plan is a sequence a[1],a[2],…,a[k], where a[i] is the department that student i joins.
The hat builds a plan like this. The departments are numbered from 0 to p−1. Write next(x) for the department after x, so next(x)=x+1 when x<p−1 and next(p−1)=0. The plan starts as a sequence with the single element 0. After each step, a sequence a with k elements becomes the sequence a[1],a[2],…,a[k],next(a[1]),next(a[2]),…,next(a[k]) with 2k 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)
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 n and p. For each pair, report the department that student n joins when the school has p departments. Students are numbered from 1.
The first line contains the number of queries Q (1≤Q≤310000).
Each of the next Q lines contains two integers n and p in that order, separated by a space (1≤n≤1018, 2≤p≤1018).
Print Q lines, one answer per query, in the order the queries are given. Each line holds the number of the department that student n joins.