This page is still under construction.

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

The Sorting Hat

Time limit1sMemory limit256 MB

Summary
Find the department of student n by counting the set bits in n-1 and taking the remainder modulo p.
Level

Medium5 of 10

Topics
Bit manipulation, Math
Solved
No attempts yet

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 p−1p-1. Write next(x)\text{next}(x) for the department after xx, so next(x)=x+1\text{next}(x) = x+1 when x<p−1x < p-1 and next(p−1)=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 (1≤Q≤310 0001 \le Q \le 310\,000).

Each of the next QQ lines contains two integers nn and pp in that order, separated by a space (1≤n≤10181 \le n \le 10^{18}, 2≤p≤10182 \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.

Examples2

  1. Example 1

    Input
    10
    1 4
    2 4
    3 4
    4 4
    5 4
    6 4
    7 4
    8 4
    9 4
    10 4
    
    Expected output
    0
    1
    1
    2
    1
    2
    2
    3
    1
    2
    
  2. Example 2

    Input
    16
    1 2
    2 2
    3 2
    4 2
    5 2
    6 2
    7 2
    8 2
    9 2
    10 2
    11 2
    12 2
    13 2
    14 2
    15 2
    16 2
    
    Expected output
    0
    1
    1
    0
    1
    0
    0
    1
    1
    0
    0
    1
    0
    1
    1
    0