Number of Common Factors - Problem
Find the Common Ground!

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
๐ŸŽฏ Common Factors via GCDNumber A12Number B6GCD(12, 6) = 6GCD6Factor: 1Factor: 2Factor: 3Factor: 6Result: 4 Common FactorsTime: O(log n + โˆšGCD) vs O(min(a,b))
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))

n
2n
โšก Linearithmic
Space Complexity
O(1)

Only using constant extra space for variables

n
2n
โœ“ 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
Asked in
Google 15 Amazon 12 Microsoft 8 Meta 6
24.7K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen