Skip to content

Commit

Permalink
Add problem 1925: Count Square Sum Triples
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed May 10, 2024
1 parent 330a572 commit deb9441
Show file tree
Hide file tree
Showing 3 changed files with 99 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1421,6 +1421,7 @@ pub mod problem_1915_number_of_wonderful_substrings;
pub mod problem_1920_build_array_from_permutation;
pub mod problem_1921_eliminate_maximum_number_of_monsters;
pub mod problem_1922_count_good_numbers;
pub mod problem_1925_count_square_sum_triples;
pub mod problem_1926_nearest_exit_from_entrance_in_maze;
pub mod problem_1929_concatenation_of_array;
pub mod problem_1935_maximum_number_of_words_you_can_type;
Expand Down
47 changes: 47 additions & 0 deletions src/problem_1925_count_square_sum_triples/brute_force.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl Solution {
pub fn count_triples(n: i32) -> i32 {
let n = u16::from(n as u8);
let mut result = 0;

for c in 5..=n {
let c_squared = c * c;
let half_c_squared = c_squared / 2;

for a in 1_u16.. {
let a_squared = a * a;

if a_squared <= half_c_squared {
let b_squared = c_squared - a_squared;

if (f32::from(b_squared).sqrt() as u16).pow(2) == b_squared {
result += 2;
}
} else {
break;
}
}
}

result
}
}

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl super::Solution for Solution {
fn count_triples(n: i32) -> i32 {
Self::count_triples(n)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
51 changes: 51 additions & 0 deletions src/problem_1925_count_square_sum_triples/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
pub mod brute_force;

pub trait Solution {
fn count_triples(n: i32) -> i32;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
// See <https://oeis.org/A063468>.
let test_cases = [
(1, 0),
(2, 0),
(3, 0),
(4, 0),
(5, 2),
(6, 2),
(7, 2),
(8, 2),
(9, 2),
(10, 4),
(11, 4),
(12, 4),
(13, 6),
(14, 6),
(15, 8),
(16, 8),
(17, 10),
(18, 10),
(19, 10),
(20, 12),
(21, 12),
(22, 12),
(23, 12),
(24, 12),
(25, 16),
(26, 18),
(27, 18),
(28, 18),
(29, 20),
(30, 22),
(31, 22),
];

for (n, expected) in test_cases {
assert_eq!(S::count_triples(n), expected);
}
}
}

0 comments on commit deb9441

Please sign in to comment.