LeetCode 2427: Number of Common Factors
Problem Description
Explanation
To find the number of common factors of two positive integers, we can iterate from 1 to the minimum of the two integers and check if the current number is a common factor of both. If it is, we increment a counter. Finally, we return the counter as the result.
- Start with a counter variable
count
set to 0. - Iterate from 1 to the minimum of
a
andb
(inclusive). - For each number
i
, check if botha
andb
are divisible byi
. - If they are, increment
count
. - Return
count
.
Time complexity: O(min(a, b))
Space complexity: O(1)
Solutions
class Solution {
public int numCommonFactors(int a, int b) {
int count = 0;
for (int i = 1; i <= Math.min(a, b); i++) {
if (a % i == 0 && b % i == 0) {
count++;
}
}
return count;
}
}
Loading editor...