Watch 10 video solutions for Number of Common Factors, a easy level problem involving Math, Enumeration, Number Theory. This walkthrough by code Explainer has 884 views views. Want to try solving it yourself? Practice on FleetCode or read the detailed text solution.
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 <= 1000Problem Overview: Given two integers a and b, return how many integers divide both numbers without leaving a remainder. A number is a common factor if a % x == 0 and b % x == 0.
Approach 1: Direct Iteration (Time: O(min(a,b)), Space: O(1))
The straightforward solution checks every possible factor from 1 to min(a, b). For each integer i, verify whether it divides both numbers using the modulo operation. If a % i == 0 and b % i == 0, increment the count. This brute-force enumeration works because any common factor cannot exceed the smaller number. The method relies purely on enumeration and basic math operations.
This approach is easy to implement and perfectly fine for small constraints. It demonstrates clear understanding of factor checking, which interviewers often expect before discussing optimizations.
Approach 2: Using GCD (Time: O(sqrt(g)), Space: O(1))
A key observation: any number that divides both a and b must also divide g = gcd(a, b). Instead of checking all numbers up to min(a,b), compute the greatest common divisor using the Euclidean algorithm from number theory. The problem then reduces to counting how many divisors g has.
To count divisors efficiently, iterate from 1 to sqrt(g). If i divides g, then both i and g / i are valid divisors (unless they are equal). Each divisor corresponds to a number that divides both a and b. This reduces the search space significantly compared to scanning all numbers up to min(a,b).
Recommended for interviews: Start with direct iteration to show you understand what a common factor means. Then move to the GCD-based solution. Using gcd(a,b) and enumerating its divisors cuts the complexity to O(sqrt(g)), which demonstrates stronger algorithmic thinking and familiarity with number theory optimizations.
| Approach | Time | Space | When to Use |
|---|---|---|---|
| Direct Iteration | O(min(a,b)) | O(1) | Simple implementation when numbers are small or constraints are low |
| Using GCD + Divisor Enumeration | O(sqrt(g)) | O(1) | Preferred optimized approach when numbers are larger and divisor counting is faster |