Skip to content

Commit

Permalink
leetcode: Add 2427
Browse files Browse the repository at this point in the history
  • Loading branch information
XuShaohua committed May 27, 2024
1 parent 045df21 commit bd8ab99
Show file tree
Hide file tree
Showing 3 changed files with 79 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/leetcode/2427.number-of-common-factors/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "lc-2427-number-of-common-factors"
version = "0.1.0"
edition = "2021"
publish = false

[dependencies]
4 changes: 4 additions & 0 deletions src/leetcode/2427.number-of-common-factors/index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@

#

[问题描述](../problems/)
68 changes: 68 additions & 0 deletions src/leetcode/2427.number-of-common-factors/src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
// Copyright (c) 2024 Xu Shaohua <[email protected]>. 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<i32> {
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);
}
}

0 comments on commit bd8ab99

Please sign in to comment.