From 8f865fa34c11b19168261ddb66ed5bf861a0d2f5 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Wed, 13 Mar 2024 22:25:22 +0100 Subject: [PATCH] =?UTF-8?q?rs:=20add=20=C2=AB2485.=20Find=20the=20Pivot=20?= =?UTF-8?q?Integer=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- rs/find-the-pivot-integer.rs | 43 ++++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 rs/find-the-pivot-integer.rs diff --git a/rs/find-the-pivot-integer.rs b/rs/find-the-pivot-integer.rs new file mode 100644 index 0000000..c671e87 --- /dev/null +++ b/rs/find-the-pivot-integer.rs @@ -0,0 +1,43 @@ +struct Solution {} +impl Solution { + pub fn pivot_integer(n: i32) -> i32 { + // S_i = S_n - S_{i - 1} + // i * (1 + i) / 2 = n * (1 + n) / 2 - i * (i - 1) / 2 + // i * (1 + i) = n * (1 + n) - i * (i - 1) + // 2i² = n(1 + n) + // i = sqrt(n * (1 + n) / 2) + + let expected_ii = n * (1 + n) / 2; + + let mut i = 1; + while i * i < expected_ii { + i += 1; + } + + if i * i == expected_ii { + return i; + } + + -1 + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn example_1() { + assert_eq!(Solution::pivot_integer(8), 6); + } + + #[test] + fn example_2() { + assert_eq!(Solution::pivot_integer(1), 1); + } + + #[test] + fn example_3() { + assert_eq!(Solution::pivot_integer(4), -1); + } +}