Number of Common Factors - Problem
Find the Common Ground!
Given two positive integers
What makes this interesting? While it might seem straightforward, this problem teaches you fundamental concepts about divisibility, greatest common divisors, and efficient factorization techniques that are crucial for more advanced number theory problems.
Goal: Return the total count of positive integers that divide both
Example: For
Given two positive integers
a and b, your task is to count how many common factors they share. A common factor is any positive integer that divides both numbers evenly (with no remainder).What makes this interesting? While it might seem straightforward, this problem teaches you fundamental concepts about divisibility, greatest common divisors, and efficient factorization techniques that are crucial for more advanced number theory problems.
Goal: Return the total count of positive integers that divide both
a and b.Example: For
a = 12 and b = 6, the factors of 12 are [1, 2, 3, 4, 6, 12] and factors of 6 are [1, 2, 3, 6]. The common factors are [1, 2, 3, 6], so the answer is 4. Input & Output
example_1.py โ Basic Case
$
Input:
a = 12, b = 6
โบ
Output:
4
๐ก Note:
Factors of 12: [1, 2, 3, 4, 6, 12]. Factors of 6: [1, 2, 3, 6]. Common factors: [1, 2, 3, 6]. Count = 4.
example_2.py โ Prime Numbers
$
Input:
a = 25, b = 30
โบ
Output:
2
๐ก Note:
GCD(25, 30) = 5. Factors of 5: [1, 5]. So there are 2 common factors.
example_3.py โ Same Numbers
$
Input:
a = 1, b = 1
โบ
Output:
1
๐ก Note:
Both numbers are 1. The only common factor is 1 itself. Count = 1.
Visualization
Tap to expand
Understanding the Visualization
1
Calculate GCD
Find the greatest common divisor using Euclidean algorithm
2
Factor the GCD
Count all factors of the GCD efficiently using square root method
3
Return Count
The factors of GCD are exactly the common factors we need
Key Takeaway
๐ฏ Key Insight: Common factors of two numbers are exactly the factors of their GCD - this transforms an O(n) enumeration problem into an O(log n + โGCD) mathematical solution!
Time & Space Complexity
Time Complexity
O(log(min(a,b)) + sqrt(GCD))
GCD computation takes O(log(min(a,b))) and factor counting takes O(sqrt(GCD))
โก Linearithmic
Space Complexity
O(1)
Only using constant extra space for variables
โ Linear Space
Constraints
- 1 โค a, b โค 1000
- Both a and b are positive integers
- Note: 1 is always a common factor of any two positive integers
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code