Skip to content

Commit 45264ea

Browse files
committed
Add problem 2614: Prime In Diagonal
1 parent 991c70c commit 45264ea

File tree

3 files changed

+81
-0
lines changed

3 files changed

+81
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1928,6 +1928,7 @@ pub mod problem_2601_prime_subtraction_operation;
19281928
pub mod problem_2602_minimum_operations_to_make_all_array_elements_equal;
19291929
pub mod problem_2609_find_the_longest_balanced_substring_of_a_binary_string;
19301930
pub mod problem_2610_convert_an_array_into_a_2d_array_with_conditions;
1931+
pub mod problem_2614_prime_in_diagonal;
19311932

19321933
#[cfg(test)]
19331934
mod test_utilities;
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
fn is_prime(num: u32) -> bool {
7+
if num < 2 {
8+
false
9+
} else {
10+
let sqrt = num.isqrt();
11+
12+
for x in 2..=sqrt {
13+
if num % x == 0 {
14+
return false;
15+
}
16+
}
17+
18+
true
19+
}
20+
}
21+
22+
pub fn diagonal_prime(nums: Vec<Vec<i32>>) -> i32 {
23+
let n = nums.len();
24+
let mut result = 0;
25+
26+
for (i, row) in nums.iter().enumerate() {
27+
let x = row[i] as u32;
28+
let y = row[n - 1 - i] as u32;
29+
30+
if Self::is_prime(x) {
31+
result = result.max(x);
32+
}
33+
34+
if Self::is_prime(y) {
35+
result = result.max(y);
36+
}
37+
}
38+
39+
result as _
40+
}
41+
}
42+
43+
// ------------------------------------------------------ snip ------------------------------------------------------ //
44+
45+
impl super::Solution for Solution {
46+
fn diagonal_prime(nums: Vec<Vec<i32>>) -> i32 {
47+
Self::diagonal_prime(nums)
48+
}
49+
}
50+
51+
#[cfg(test)]
52+
mod tests {
53+
#[test]
54+
fn test_solution() {
55+
super::super::tests::run::<super::Solution>();
56+
}
57+
}
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
pub mod iterative;
2+
pub mod sieve_of_eratosthenes;
3+
4+
pub trait Solution {
5+
fn diagonal_prime(nums: Vec<Vec<i32>>) -> i32;
6+
}
7+
8+
#[cfg(test)]
9+
mod tests {
10+
use super::Solution;
11+
use crate::test_utilities::Matrix;
12+
13+
pub fn run<S: Solution>() {
14+
let test_cases = [
15+
(&[[1, 2, 3], [5, 6, 7], [9, 10, 11]] as &dyn Matrix<_>, 11),
16+
(&[[1, 2, 3], [5, 17, 7], [9, 11, 10]], 17),
17+
];
18+
19+
for (nums, expected) in test_cases {
20+
assert_eq!(S::diagonal_prime(nums.to_vec()), expected);
21+
}
22+
}
23+
}

0 commit comments

Comments
 (0)