Skip to content

Commit 9594885

Browse files
committed
Add problem 2761: Prime Pairs With Target Sum
1 parent 33324b2 commit 9594885

File tree

3 files changed

+69
-0
lines changed

3 files changed

+69
-0
lines changed

src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1959,6 +1959,7 @@ pub mod problem_2739_total_distance_traveled;
19591959
pub mod problem_2740_find_the_value_of_the_partition;
19601960
pub mod problem_2744_find_maximum_number_of_string_pairs;
19611961
pub mod problem_2760_longest_even_odd_subarray_with_threshold;
1962+
pub mod problem_2761_prime_pairs_with_target_sum;
19621963

19631964
#[cfg(test)]
19641965
mod test_utilities;
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
pub mod sieve_of_eratosthenes;
2+
3+
pub trait Solution {
4+
fn find_prime_pairs(n: i32) -> Vec<Vec<i32>>;
5+
}
6+
7+
#[cfg(test)]
8+
mod tests {
9+
use super::Solution;
10+
11+
pub fn run<S: Solution>() {
12+
let test_cases = [(10, &[[3, 7], [5, 5]] as &[_]), (2, &[])];
13+
14+
for (n, expected) in test_cases {
15+
assert_eq!(S::find_prime_pairs(n), expected);
16+
}
17+
}
18+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
pub struct Solution;
2+
3+
// ------------------------------------------------------ snip ------------------------------------------------------ //
4+
5+
impl Solution {
6+
pub fn find_prime_pairs(n: i32) -> Vec<Vec<i32>> {
7+
let n = n as u32 as usize;
8+
let mut result = Vec::new();
9+
10+
if n >= 4 {
11+
let mut is_composites = vec![false; n - 3].into_boxed_slice();
12+
13+
for step in 2..=n.isqrt() {
14+
if !is_composites[step - 2] {
15+
let mut i = step * step - 2;
16+
17+
while let Some(is_composite) = is_composites.get_mut(i) {
18+
*is_composite = true;
19+
i += step;
20+
}
21+
}
22+
}
23+
24+
result.extend(
25+
(2..)
26+
.zip(is_composites[..n / 2 - 1].iter().zip(is_composites.iter().rev()))
27+
.filter(|&(_, (&lhs_is_composite, &rhs_is_composite))| !lhs_is_composite && !rhs_is_composite)
28+
.map(|(lhs, _)| vec![lhs, n as i32 - lhs]),
29+
);
30+
}
31+
32+
result
33+
}
34+
}
35+
36+
// ------------------------------------------------------ snip ------------------------------------------------------ //
37+
38+
impl super::Solution for Solution {
39+
fn find_prime_pairs(n: i32) -> Vec<Vec<i32>> {
40+
Self::find_prime_pairs(n)
41+
}
42+
}
43+
44+
#[cfg(test)]
45+
mod tests {
46+
#[test]
47+
fn test_solution() {
48+
super::super::tests::run::<super::Solution>();
49+
}
50+
}

0 commit comments

Comments
 (0)