Cyclic Triangle

Given a triangle size and cell coordinates, report the digit placed at that cell by the spiral border-filling order.

Medium5MathImplementationSimulationNo attempts yetTime limit5sMemory limit512 MB

Problem

A right triangle grid of size NN is filled with digits. Both legs have length NN. One leg lies horizontally along the top, the other lies vertically along the right side. Columns are numbered 00 at the left end through N1N-1 at the right end, and rows are numbered 00 at the top through N1N-1 at the bottom. The right angle is therefore at row 00, column N1N-1, and the cell at row RR, column CC exists only when RCR \le C. The hypotenuse runs from row 00, column 00 to row N1N-1, column N1N-1.

The filling walks once around the border of the triangle.

  1. Start at row 00, column 00, the end of the horizontal leg opposite the right angle, and fill rightward along that leg up to row 00, column N1N-1.
  2. Continue downward along the vertical leg to row N1N-1, column N1N-1.
  3. Then move up and to the left along the hypotenuse, filling as far as row 11, column 11.

The cells that are still empty now form a right triangle of size N3N-3 whose top left corner is row 11, column 22. Apply the same rule to that triangle, and stop once the size drops to 00 or below.

The digits follow the filling order and repeat as 1,2,,9,0,1,2,1, 2, \dots, 9, 0, 1, 2, \dots. The kk-th cell filled gets the remainder of kk divided by 1010.

For N=10N = 10 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 NN is known, the digit in any cell can be found directly. In the table above, row 00, column 77 holds 88, and row 55, column 77 holds 22. 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 TT (1T101 \le T \le 10).

The first line of each test case contains the triangle size NN and the number of queries QQ, separated by a single space (1N10000001 \le N \le 1000000, 1Q101 \le Q \le 10).

Each of the next QQ lines contains a row index RR and a column index CC, separated by a single space (0RC<N0 \le R \le C < N). Rows and columns are both counted from 00.

Output

For each query print the digit written in the cell at row RR, column CC, one per line, in the order the queries are given.