[LeetCode] Number of Common Factors

2427. Number of Common Factors

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
class Solution {
public:
int commonFactors(int a, int b) {
int g = __gcd(a,b);
int res = 0;
for(int i = 1; i <= sqrt(g); i++) {
if(g % i) continue;
res += 1;
if(i * i != g) res += 1;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/02/PS/LeetCode/number-of-common-factors/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.