Given two positive integers a
and b
, return the number of common factors of a
and b
.
An integer x
is a common factor of a
and b
if x
divides both a
and b
.
Example 1:
Input: a = 12, b = 6 Output: 4 Explanation: The common factors of 12 and 6 are 1, 2, 3, 6.
Example 2:
Input: a = 25, b = 30 Output: 2 Explanation: The common factors of 25 and 30 are 1, 5.
Constraints:
1 <= a, b <= 1000
这题就是求两个数字的所有共同约数,就是同时能被a和b整除。最最简单的做法就是从1遍历到两个数里更小的那个,每个数字除一下判断一下就行。
class Solution {
public int commonFactors(int a, int b) {
int result = 0;
int min = Math.min(a, b);
for (int i = 1; i <= min; i++) {
if (a % i == 0 && b % i == 0) {
result++;
}
}
return result;
}
}
也有人用gcd先求出上限,然后再遍历的,我觉得可以但没必要?以及永远也记不住gcd的算法。这次试图理解了一下,大概就是repeatedly replace the larger number with the diff between the larger and the smaller number。
class Solution {
public int commonFactors(int a, int b) {
int result = 0;
int gcd = gcd(a, b);
for (int i = 1; i <= gcd; i++) {
if (gcd % i == 0) {
result++;
}
}
return result;
}
private int gcd(int a, int b) {
if (b == 0) {
return a;
} else {
return gcd(b, a % b);
}
}
}