[LeetCode] Prime In Diagonal

2614. Prime In Diagonal

You are given a 0-indexed two-dimensional integer array nums.

Return the largest prime number that lies on at least one of the diagonals of nums. In case, no prime is present on any of the diagonals, return 0.

Note that:

  • An integer is prime if it is greater than 1 and has no positive integer divisors other than 1 and itself.
  • An integer val is on one of thediagonals of nums if there exists an integer i for which nums[i][i] = val or an i for which nums[i][nums.length - i - 1]= val.

img

In the above diagram, one diagonal is [1,5,9] and another diagonal is [3,5,7].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
bool prime(int k) {
if(k == 1) return false;
for(int i = 2; i * i <= k; i++) {
if(k % i) continue;
return false;
}
return true;
}
public:
int diagonalPrime(vector<vector<int>>& nums) {
int n = nums.size(), m = nums[0].size(), res = 0;
for(int i = 0; i < n; i++) for(int j = 0; j < m; j++) {
if(nums[i][j] <= res) continue;
if(i == j or (n - i - 1 == j)) {
if(prime(nums[i][j])) res = nums[i][j];
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/04/09/PS/LeetCode/prime-in-diagonal/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.