2427.公因子的数目
链接:2427.公因子的数目
难度:Easy
标签:数学、枚举、数论
简介:给你两个正整数 a 和 b ,返回 a 和 b 的 公 因子的数目。如果 x 可以同时整除 a 和 b ,则认为 x 是 a 和 b 的一个 公因子 。
题解 1 - python
- 编辑时间:2023-04-05
- 执行用时:44ms
- 内存消耗:14.9MB
- 编程语言:python
- 解法介绍:同上。
class Solution:
    def commonFactors(self, a: int, b: int) -> int:
        return len([i for i in range(1, min(a, b) + 1) if a % i == 0 and b % i == 0])
  
题解 2 - rust
- 编辑时间:2023-04-05
- 内存消耗:1.9MB
- 编程语言:rust
- 解法介绍:同上。
impl Solution {
    pub fn common_factors(a: i32, b: i32) -> i32 {
        (1..=a.min(b))
            .into_iter()
            .filter(|v| a % v == 0 && b % v == 0)
            .collect::<Vec<i32>>()
            .len() as i32
    }
}
题解 3 - cpp
- 编辑时间:2023-04-05
- 执行用时:4ms
- 内存消耗:5.8MB
- 编程语言:cpp
- 解法介绍:遍历。
class Solution {
public:
    int commonFactors(int a, int b) {
        int res = 0;
        for (int i = 1; i <= min(a, b); i++) {
            if (a % i == 0 && b % i == 0) res++;
        }
        return res;
    }
};