Ctrl K

Largest Prime on the Diagonals

Easy
You are given an n × n grid grid of positive integers. Consider its two diagonals: the main one, cells grid[i][i], and the anti-diagonal, cells grid[i][n - 1 - i]. Return the largest prime number found on at least one of the diagonals. If neither diagonal holds a prime, return 0. A prime is greater than 1 and divisible only by 1 and itself.
Example 1
grid=[[7, 4, 9], [6, 8, 2], [13, 5, 10]] → 13

The diagonals hold 7, 8, 10, 9 and 13. Of these, 7 and 13 are prime, and the larger is 13.

Example 2
grid=[[4, 3], [5, 1]] → 5

In a 2×2 grid the main diagonal holds 4 and 1, the other one holds 3 and 5. The answer is 5.

Example 3
grid=[[1, 2], [3, 9]] → 3

The primes 2 and 3 sit on the anti-diagonal, so the answer is 3. Had the diagonals held only 1 and 9, the answer would be 0.

Constraints
  • 1 ≤ n ≤ 300
  • len(grid[i]) = n
  • 1 ≤ grid[i][j] ≤ 4 · 10⁶
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsPrimes Along Grid Rays MediumShadows of Block Towers EasySurface of Cube Towers EasyEven Piles of Cards EasyHow a Rumor Spreads Easy
loading Python…
Input
grid=[[7, 4, 9], [6, 8, 2], [13, 5, 10]]
Expected
13

Run checks the first 3 tests in your browser. Submit checks all 72 tests on the server, hidden ones included.