diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 32f26cd..884c7e6 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -78,4 +78,5 @@ mod p2312_selling_pieces_of_wood; mod p2684_maximum_number_of_moves_in_a_grid; mod p310_minimum_height_trees; mod p303_range_sum_query_immutable; -mod p1793_maximum_score_of_a_good_subarray; \ No newline at end of file +mod p1793_maximum_score_of_a_good_subarray; +mod p1969_minimum_non_zero_product_of_the_array_elements; \ No newline at end of file diff --git a/src/problem/p1969_minimum_non_zero_product_of_the_array_elements.rs b/src/problem/p1969_minimum_non_zero_product_of_the_array_elements.rs new file mode 100644 index 0000000..bebf9d9 --- /dev/null +++ b/src/problem/p1969_minimum_non_zero_product_of_the_array_elements.rs @@ -0,0 +1,55 @@ +use std::convert::TryInto; + +/** + * [1969] Minimum Non-Zero Product of the Array Elements + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn min_non_zero_product(p: i32) -> i32 { + let p = p as i64; + if p == 1 { + return 1; + } + + let m = 1e9 as i64 + 7; + let x = Solution::fast_power(2, p, m) - 1; + let y = 1 << (p - 1); + dbg!(x, y); + + return (Solution::fast_power(x - 1, y - 1, m) * x % m).try_into().unwrap(); + } + + fn fast_power(x: i64, n: i64, m: i64) -> i64 { + let mut result = 1; + let mut n = n; + let mut x = x; + + while n != 0 { + if n & 1 != 0 { + result = result * x % m; + } + + x = x * x % m; + n = n >> 1; + } + + result + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_1969() { + assert_eq!(1, Solution::min_non_zero_product(1)); + assert_eq!(6, Solution::min_non_zero_product(2)); + } +}