Harry Potter and the Sorting Hat
InterviewTime limit2sMemory limit1024 MB
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 of them. The hat still does the sorting.
Before the ceremony, the hat prepares a plan in advance. The plan is a sequence , where is the number of the house that the -th student goes to.
The hat numbers the houses from to . The house after house is house , and the house after house is house . The first version of the plan contains only house . 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: , , , , . The length of the last plan is enough for all students, so the hat does not build any further plans.
For the -th student, find the house among the houses that the hat assigns.
Input
The first line contains the number of queries (). Each of the next lines contains two integers and (, ), where is the student number and is the number of houses.
Output
For each query, print the house number assigned to the -th student on its own line.