Number of Common Factors - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: a = 12, b = 18
Output: 4
💡 Note: Common factors are 1, 2, 3, and 6. Both 12 and 18 are divisible by each of these numbers.
Example 2 — Small Numbers
$ Input: a = 25, b = 30
Output: 2
💡 Note: Common factors are 1 and 5. GCD(25,30) = 5, and 5 has factors 1 and 5.
Example 3 — Coprime Numbers
$ Input: a = 7, b = 13
Output: 1
💡 Note: 7 and 13 are prime numbers with no common factors except 1.

Constraints

  • 1 ≤ a, b ≤ 1000

Visualization

Tap to expand
Number of Common Factors INPUT Two positive integers a = 12 b = 18 Factors of 12: 1, 2, 3, 4, 6, 12 Factors of 18: 1, 2, 3, 6, 9, 18 GCD(12, 18) = 6 Factors of GCD: 1,2,3,6 a = 12, b = 18 Find common factors ALGORITHM STEPS 1 Calculate GCD GCD(12,18) = 6 2 Find sqrt(GCD) sqrt(6) ~ 2.45 3 Loop i: 1 to sqrt Check if i divides GCD 4 Count pairs Add i and GCD/i Iteration Details (GCD=6) i 6%i 6/i count 1 0 6 +2 2 0 3 +2 Factors found: 1, 2, 3, 6 = 4 total FINAL RESULT Common Factors of 12 and 18 1 2 3 6 Verification: 12 % 1 = 0, 18 % 1 = 0 [OK] 12 % 2 = 0, 18 % 2 = 0 [OK] 12 % 3 = 0, 18 % 3 = 0 [OK] 12 % 6 = 0, 18 % 6 = 0 [OK] Output: 4 4 common factors found Time: O(sqrt(min(a,b))) Key Insight: A common factor of a and b must also divide their GCD. By finding factors of GCD(a,b) instead of checking all numbers up to min(a,b), we reduce the search space significantly. Using sqrt optimization, we only iterate up to sqrt(GCD), finding factor pairs (i, GCD/i) simultaneously for O(sqrt(GCD)) time. TutorialsPoint - Number of Common Factors | GCD + Square Root Optimization
Asked in
Google 15 Microsoft 12
25.0K Views
Medium Frequency
~10 min Avg. Time
850 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