The Sorting Hat
Time limit1sMemory limit256 MB
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 of them. The hat still does the sorting.
A sorting plan is a sequence , where is the department that student joins.
The hat builds a plan like this. The departments are numbered from to . Write for the department after , so when and . The plan starts as a sequence with the single element . After each step, a sequence with elements becomes the sequence with elements.
Here is how 9 students are sorted into 4 departments. The hat grows the plan in this order:
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 and . For each pair, report the department that student joins when the school has departments. Students are numbered from 1.
Input
The first line contains the number of queries ().
Each of the next lines contains two integers and in that order, separated by a space (, ).
Output
Print lines, one answer per query, in the order the queries are given. Each line holds the number of the department that student joins.