CF BUDDY
← Problems·

1838C · No Prime Differences

1400 · constructive algorithms, math, number theory

Problem: You are given integers nn and mm. Fill an nn by mm grid with the integers 11 through nmn\cdot m, in such a way that for any two adjacent cells in the grid, the absolute difference of the values in those cells is not a prime number. Two cells in the grid are considered adjacent if they share a side.

It can be shown that under the given constraints, there is always a solution.

Input Format: The first line of the input contains a single integer tt (1t10001 \le t \le 1000) — the number of test cases. The description of the test cases follows.

The first and only line of each test case contains two integers nn and mm (4n,m10004 \le n, m \le 1000) — the dimensions of the grid.

It is guaranteed that the sum of nmn\cdot m over all test cases does not exceed 10610^6.

Output Format: For each test case, output nn lines of mm integers each, representing the final grid. Every number from 11 to nmn\cdot m should appear exactly once in the grid.

The extra spaces and blank lines in the sample output below are only present to make the output easier to read, and are not required.

If there are multiple solutions, print any of them.

Note: The first sample case corresponds to the picture above. The only absolute differences between adjacent elements in this grid are 11, 44, 66, 88, and 99, none of which are prime.

Sample Cases

Case 1

Input

3
4 4
5 7
6 4

Output

16  7  1  9
12  8  2  3
13  4 10 11
14  5  6 15

29 23 17  9  5  6  2
33 27 21 15 11  7  1
32 31 25 19 20 16 10
26 30 24 18 14  8  4
35 34 28 22 13 12  3

 2  3  7 11
 8  9  1 10
17 13  5  4
18 14  6 12
19 23 15 21
20 24 16 22

Similar problems

00:00:00
Loading editor…
Welcome! I'm your coding tutor for this problem. Use the chips below to reveal stored hints or get AI feedback on your code. I'll guide you step by step — never giving away the solution.

Sign in to unlock AI tutor feedback