From bd8ab99838a2133637af0a91d97816abf11b25c0 Mon Sep 17 00:00:00 2001 From: Xu Shaohua Date: Mon, 27 May 2024 19:19:03 +0800 Subject: [PATCH] leetcode: Add 2427 --- .../2427.number-of-common-factors/Cargo.toml | 7 ++ .../2427.number-of-common-factors/index.md | 4 ++ .../2427.number-of-common-factors/src/main.rs | 68 +++++++++++++++++++ 3 files changed, 79 insertions(+) create mode 100644 src/leetcode/2427.number-of-common-factors/Cargo.toml create mode 100644 src/leetcode/2427.number-of-common-factors/index.md create mode 100644 src/leetcode/2427.number-of-common-factors/src/main.rs diff --git a/src/leetcode/2427.number-of-common-factors/Cargo.toml b/src/leetcode/2427.number-of-common-factors/Cargo.toml new file mode 100644 index 000000000..326b1571a --- /dev/null +++ b/src/leetcode/2427.number-of-common-factors/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "lc-2427-number-of-common-factors" +version = "0.1.0" +edition = "2021" +publish = false + +[dependencies] diff --git a/src/leetcode/2427.number-of-common-factors/index.md b/src/leetcode/2427.number-of-common-factors/index.md new file mode 100644 index 000000000..77a618ba8 --- /dev/null +++ b/src/leetcode/2427.number-of-common-factors/index.md @@ -0,0 +1,4 @@ + +# + +[问题描述](../problems/) diff --git a/src/leetcode/2427.number-of-common-factors/src/main.rs b/src/leetcode/2427.number-of-common-factors/src/main.rs new file mode 100644 index 000000000..f336abe28 --- /dev/null +++ b/src/leetcode/2427.number-of-common-factors/src/main.rs @@ -0,0 +1,68 @@ +// Copyright (c) 2024 Xu Shaohua . All rights reserved. +// Use of this source is governed by General Public License that can be found +// in the LICENSE file. + +#![allow(dead_code)] + +#[must_use] +fn get_factors(num: i32) -> Vec { + let mut factors = Vec::new(); + for i in 1..=num { + if num % i == 0 { + factors.push(i); + } + } + factors +} + +#[must_use] +fn get_factors_count(num: i32) -> i32 { + let mut count: i32 = 0; + for i in 1..=num { + if num % i == 0 { + count += 1; + } + } + count +} + +#[must_use] +const fn gcd(a: i32, b: i32) -> i32 { + let (mut nom, mut denom) = if a > b { (a, b) } else { (b, a) }; + + while denom != 0 { + let rem: i32 = nom % denom; + nom = denom; + denom = rem; + } + nom +} + +pub fn common_factors1(a: i32, b: i32) -> i32 { + debug_assert!((1..=1000).contains(&a)); + debug_assert!((1..=1000).contains(&b)); + + let common_divisor: i32 = gcd(a, b); + get_factors_count(common_divisor) +} + +pub type SolutionFn = fn(i32, i32) -> i32; + +fn check_common_factors(func: SolutionFn) { + assert_eq!(func(12, 6), 4); + assert_eq!(func(25, 30), 2); +} + +fn main() { + check_common_factors(common_factors1); +} + +#[cfg(test)] +mod tests { + use super::{check_common_factors, common_factors1}; + + #[test] + fn test_common_factors1() { + check_common_factors(common_factors1); + } +}