Cyclic Triangle
Time limit5sMemory limit512 MB
Given a triangle size and cell coordinates, report the digit placed at that cell by the spiral border-filling order.
- Level
Medium5 of 10
- Topics
- Math, Implementation, Simulation
- Solved
- No attempts yet
Problem
A right triangle grid of size is filled with digits. Both legs have length . One leg lies horizontally along the top, the other lies vertically along the right side. Columns are numbered at the left end through at the right end, and rows are numbered at the top through at the bottom. The right angle is therefore at row , column , and the cell at row , column exists only when . The hypotenuse runs from row , column to row , column .
The filling walks once around the border of the triangle.
- Start at row , column , the end of the horizontal leg opposite the right angle, and fill rightward along that leg up to row , column .
- Continue downward along the vertical leg to row , column .
- Then move up and to the left along the hypotenuse, filling as far as row , column .
The cells that are still empty now form a right triangle of size whose top left corner is row , column . Apply the same rule to that triangle, and stop once the size drops to or below.
The digits follow the filling order and repeat as . The -th cell filled gets the remainder of divided by .
For the finished table is shown below. A dot marks a position outside the triangle.
1234567890
.789012341
..65678952
...5445063
....433174
.....32285
......2196
.......107
........08
.........9

Once is known, the digit in any cell can be found directly. In the table above, row , column holds , and row , column holds . Given a row index and a column index, report the digit written in that cell.
Input
The first line contains the number of test cases ().
The first line of each test case contains the triangle size and the number of queries , separated by a single space (, ).
Each of the next lines contains a row index and a column index , separated by a single space (). Rows and columns are both counted from .
Output
For each query print the digit written in the cell at row , column , one per line, in the order the queries are given.