1 Star 0 Fork 332

卜月航 / leetcode

forked from doocs / leetcode 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
README.md 2.58 KB
一键复制 编辑 原始数据 按行查看 历史
ylb 提交于 2022-10-12 19:34 . feat: update lc problems

2427. 公因子的数目

English Version

题目描述

给你两个正整数 ab ,返回 ab 因子的数目。

如果 x 可以同时整除 ab ,则认为 xab 的一个 公因子

 

示例 1:

输入:a = 12, b = 6
输出:4
解释:12 和 6 的公因子是 1、2、3、6 。

示例 2:

输入:a = 25, b = 30
输出:2
解释:25 和 30 的公因子是 1、5 。

 

提示:

  • 1 <= a, b <= 1000

解法

方法一:枚举

直接枚举 $[1, 1000]$ 中的每个数,判断其是否是 $a$ 和 $b$ 的公因子,如果是,则答案加一。

时间复杂度 $O(n)$。本题中 $n = 1000$。

Python3

class Solution:
    def commonFactors(self, a: int, b: int) -> int:
        return sum(a % i == 0 and b % i == 0 for i in range(1, 1001))

Java

class Solution {
    public int commonFactors(int a, int b) {
        int ans = 0, n = Math.min(a, b);
        for (int i = 1; i <= n; ++i) {
            if (a % i == 0 && b % i == 0) {
                ++ans;
            }
        }
        return ans;
    }
}

C++

class Solution {
public:
    int commonFactors(int a, int b) {
        int ans = 0;
        int n = min(a, b);
        for (int i = 1; i <= n; ++i) {
            if (a % i == 0 && b % i == 0) {
                ++ans;
            }
        }
        return ans;
    }
};

Go

func commonFactors(a int, b int) int {
	ans := 0
	for i := 1; i <= a && i <= b; i++ {
		if a%i == 0 && b%i == 0 {
			ans++
		}
	}
	return ans
}

TypeScript

function commonFactors(a: number, b: number): number {
    const n = Math.min(a, b);
    let ans = 0;
    for (let i = 1; i <= n; i++) {
        if (a % i == 0 && b % i == 0) ans += 1;
    }
    return ans;
}

...

马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/BuYh/leetcode.git
git@gitee.com:BuYh/leetcode.git
BuYh
leetcode
leetcode
main

搜索帮助

344bd9b3 5694891 D2dac590 5694891