一、题目
给你两个正整数 a 和 b ,返回 a 和 b 的 公 因子的数目。
如果 x 可以同时整除 a 和 b ,则认为 x 是 a 和 b 的一个 公因子 。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/number-of-common-factors/description/
二、C++解法
我的思路及代码
最大公约数就是找到能够被整除的数字就行咯
class Solution {
public:
int commonFactors(int a, int b) {
int ans=0;
int min = a>b?b:a;
for(int i=1;i<=min;i++){
if(a%i == 0&&b%i == 0){
ans++;
}
}
return ans;
}
};
- 时间复杂度:O(n),其中 n 是给定输入 a 和 b 的范围
- 空间复杂度:O(1)
官方参考代码
class Solution {
public:
int commonFactors(int a, int b) {
int c = gcd(a, b), ans = 0;
for (int x = 1; x * x <= c; ++x) {
if (c % x == 0) {
++ans;
if (x * x != c) {
++ans;
}
}
}
return ans;
}
};