Under construction

Still being built. Things may change

Harry Potter and the Sorting Hat

Interview

Time limit2sMemory limit1024 MB

Summary
Given n and p, find the house of the n-th student, where the house is the number of 1 bits in n-1 taken modulo p.
Level

Medium4 of 10

Topics
Bit manipulation, Math
Solved
No attempts yet

Problem

Since ancient times, a magic hat has sorted students into houses. Earlier the school had four houses, but after recent reforms there are pp of them. The hat still does the sorting.

Before the ceremony, the hat prepares a plan in advance. The plan is a sequence a1,a2,…,aka_1, a_2, \ldots, a_k, where aia_i is the number of the house that the ii-th student goes to.

The hat numbers the houses from 00 to p−1p-1. The house after house ii is house (i+1)(i+1), and the house after house (p−1)(p-1) is house 00. The first version of the plan contains only house 00. After that, the hat repeatedly appends the current plan to its own end, replacing each house with the next one.

Consider sorting nine students into four houses. The hat builds these plans in order: (0)(0), (0,1)(0, 1), (0,1,1,2)(0, 1, 1, 2), (0,1,1,2,1,2,2,3)(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, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 0). The length of the last plan is enough for all students, so the hat does not build any further plans.

For the nn-th student, find the house among the pp houses that the hat assigns.

Input

The first line contains the number of queries qq (1≤q≤100,0001 \le q \le 100{,}000). Each of the next qq lines contains two integers nn and pp (1≤n≤10181 \le n \le 10^{18}, 2≤p≤10182 \le p \le 10^{18}), where nn is the student number and pp is the number of houses.

Output

For each query, print the house number assigned to the nn-th student on its own line.

Examples1

  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