Leetcode 2427. Number of Common Factors
LeetCode Problem 2427: Number of Common Factors
Given two positive integers a
and b
, return the number of common factors of a
and b
.
A common factor of a
and b
is any integer that divides both a
and b
exactly (i.e., without leaving a remainder).
a
and b
guaranteed to be positive?a
and b
?public class CommonFactors {
public int commonFactors(int a, int b) {
int gcdValue = gcd(a, b);
int commonFactorCount = 0;
// Only need to check up to gcdValue since it is the highest possible common factor
for (int i = 1; i <= gcdValue; i++) {
if (a % i == 0 && b % i == 0) {
commonFactorCount++;
}
}
return commonFactorCount;
}
// Helper method to calculate the Greatest Common Divisor (GCD) using Euclidean algorithm
private int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static void main(String[] args) {
CommonFactors solution = new CommonFactors();
System.out.println(solution.commonFactors(12, 15)); // Output should be 2 (factors are 1 and 3)
System.out.println(solution.commonFactors(100, 50)); // Output should be 6 (factors are 1, 2, 5, 10, 20, 50)
}
}
a
and b
using the Euclidean algorithm.i
in this range, check if it divides both a
and b
exactly.i
divides both a
and b
.Thus, the overall time complexity is O(log(min(a, b)) + GCD(a, b)).
By leveraging the GCD, we limit the range of integers we need to check, making the solution efficient for large inputs.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?