Skip to content

2427. Number of Common Factors 👍

  • Time: $O(\texttt{gcd(a, b)})$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution {
 public:
  int commonFactors(int a, int b) {
    int ans = 1;
    const int gcd = __gcd(a, b);
    for (int i = 2; i <= gcd; ++i)
      if (a % i == 0 && b % i == 0)
        ++ans;
    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public int commonFactors(int a, int b) {
    int ans = 1;
    final int gcd = gcd(a, b);
    for (int i = 2; i <= gcd; ++i)
      if (a % i == 0 && b % i == 0)
        ++ans;
    return ans;
  }

  private int gcd(int a, int b) {
    return b == 0 ? a : gcd(b, a % b);
  }
}
1
2
3
4
5
class Solution:
  def commonFactors(self, a: int, b: int) -> int:
    gcd = math.gcd(a, b)
    return sum(a % i == 0 and b % i == 0
               for i in range(1, gcd + 1))