You are given a square grid of n rows and n columns, where each cell holds a positive integer reading (for example, sensor values recorded across a square tile floor). Two diagonals cross the grid: the main diagonal, running from the top-left cell to the bottom-right cell, and the anti-diagonal, running from the top-right cell to the bottom-left cell. A cell lies on the main diagonal when its row index equals its column index, and on the anti-diagonal when its row index plus its column index equals n-1 (using 0-based indexing); the single center cell of an odd-sized grid lies on both.
Determine the largest value that is both a prime number and located on at least one of the two diagonals. If no diagonal cell holds a prime value, report 0 instead.
The first line contains one integer n. Each of the next n lines contains n space-separated integers: the values of that row of the grid, from column 1 to column n.
Print a single integer: the largest prime value found on either diagonal, or 0 if no diagonal cell is prime.
Example 1
Input
3 2 4 6 8 5 10 12 14 3
Expected
5
Explanation
The main diagonal cells are 2, 5, 3 (rows 0,1,2 at matching columns) and the anti-diagonal cells are 6, 5, 12. Among these diagonal values {2,5,3,6,12}, the primes are 2, 3, and 5, so the largest prime diagonal value is 5.
Example 2
Input
2 4 6 6 4
Expected
0
Explanation
The main diagonal cells are 4 and 4; the anti-diagonal cells are 6 and 6. None of the diagonal values {4,6} is prime, so the answer is 0.
Ready to solve this?
Sign in to open the editor, run your code against the sample tests, and submit against the full test suite.
Sign in to solve →