CF BUDDY
← Problems·

1955G · GCD on a grid

1900 · brute force, dfs and similar, dp

Problem: Not long ago, Egor learned about the Euclidean algorithm for finding the greatest common divisor of two numbers. The greatest common divisor of two numbers aa and bb is the largest number that divides both aa and bb without leaving a remainder. With this knowledge, Egor can solve a problem that he once couldn't.

Vasily has a grid with nn rows and mm columns, and the integer aij{a_i}_j is located at the intersection of the ii-th row and the jj-th column. Egor wants to go from the top left corner (at the intersection of the first row and the first column) to the bottom right corner (at the intersection of the last row and the last column) and find the greatest common divisor of all the numbers along the path. He is only allowed to move down and to the right. Egor has written down several paths and obtained different GCD values. He became interested in finding the maximum possible GCD.

Unfortunately, Egor is tired of calculating GCDs, so he asks for your help in finding the maximum GCD of the integers along the path from the top left corner to the bottom right corner of the grid.

Input Format: The first line contains an integer tt (1t1041 \le t \le {10}^{4}) — the number of test cases.

The first line of each test case contains two integers nn and mm (1n,m1001 \le n, m \le 100) — the number of rows and columns of the grid.

Then, there are nn lines, where the ii-th line contains mm integers (1ai,j106(1 \le a_{i,j} \le {10}^{6}) — the integers written in the ii-th row and the jj-th column of the grid.

It is guaranteed that the sum of nmn \cdot m does not exceed 21052 \cdot {10}^{5} over all test cases.

Output Format: For each test case, output the maximum possible GCD along the path from the top left cell to the bottom right cell in a separate line.

Sample Cases

Case 1

Input

3
2 3
30 20 30
15 25 40
3 3
12 4 9
3 12 2
8 3 12
2 4
2 4 6 8
1 3 6 9

Output

10
3
1

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