LeetCode 题解工作台
公因子的数目
给你两个正整数 a 和 b ,返回 a 和 b 的 公 因子的数目。 如果 x 可以同时整除 a 和 b ,则认为 x 是 a 和 b 的一个 公因子 。 示例 1: 输入: a = 12, b = 6 输出: 4 解释: 12 和 6 的公因子是 1、2、3、6 。 示例 2: 输入: a = 2…
3
题型
5
代码语言
3
相关题
当前训练重点
简单 · 数学·结合·enumeration
答案摘要
我们可以先算出 和 的最大公约数 ,然后枚举 中的每个数,判断其是否是 的因子,如果是,则答案加一。 时间复杂度 $O(\min(a, b))$,空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 数学·结合·enumeration 题型思路
题目描述
给你两个正整数 a 和 b ,返回 a 和 b 的 公 因子的数目。
如果 x 可以同时整除 a 和 b ,则认为 x 是 a 和 b 的一个 公因子 。
示例 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
解题思路
方法一:枚举
我们可以先算出 和 的最大公约数 ,然后枚举 中的每个数,判断其是否是 的因子,如果是,则答案加一。
时间复杂度 ,空间复杂度 。
class Solution:
def commonFactors(self, a: int, b: int) -> int:
g = gcd(a, b)
return sum(g % x == 0 for x in range(1, g + 1))
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Looking for a straightforward brute force solution with correct divisor identification.
- question_mark
Candidates should mention optimization techniques such as using GCD or divisor sets.
- question_mark
Candidates should clearly demonstrate an understanding of how to efficiently find common factors.
常见陷阱
外企场景- error
Forgetting to check all integers up to min(a, b), potentially missing some factors.
- error
Incorrectly assuming that a number is a common divisor without verifying divisibility by both a and b.
- error
Overcomplicating the solution with unnecessary steps instead of using simple divisor logic.
进阶变体
外企场景- arrow_right_alt
What if the values of a and b are large, say in the range of 1,000,000?
- arrow_right_alt
How can this approach be adjusted to handle non-integer inputs (e.g., floating-point numbers or negative numbers)?
- arrow_right_alt
Can we modify this problem to find the greatest common divisor instead of counting all common divisors?