Magicsheet logo

Number of Common Factors

Easy
12.5%
Updated 8/1/2025

Number of Common Factors

What is this problem about?

The Number of Common Factors problem asks you to count the number of integers that are factors of both a and b. An integer x is a common factor if it divides both a and b without remainder. This Number of Common Factors coding problem is a clean number theory exercise involving GCD and factor enumeration.

Why is this asked in interviews?

Microsoft, Meta, Amazon, and Google ask this easy problem to test number theory fundamentals — specifically, understanding that the common factors of a and b are exactly the factors of gcd(a, b). The math, number theory, and enumeration interview pattern is demonstrated here with a clean GCD insight.

Algorithmic pattern used

GCD + factor enumeration. Compute g = gcd(a, b). Then count the divisors of g by iterating from 1 to sqrt(g). For each i that divides g, count both i and g/i (if they're different). This reduces an O(min(a,b)) scan to O(sqrt(gcd(a,b))).

Example explanation

a=12, b=8. gcd(12,8)=4. Divisors of 4: 1, 2, 4. Count = 3. Verify: 1 divides both ✓, 2 divides both ✓, 4 divides both ✓, 3 divides 12 but not 8 ✗.

a=25, b=30. gcd=5. Divisors of 5: 1, 5. Count = 2.

Common mistakes candidates make

  • Iterating up to min(a,b) instead of sqrt(gcd(a,b)) (much slower for large inputs).
  • Not using GCD at all — checking every number for divisibility of both a and b separately.
  • Counting duplicate divisors when i == g/i (perfect square case).
  • Using Euclidean GCD incorrectly (remember: gcd(a,0) = a as base case).

Interview preparation tip

Common factors equal divisors of GCD — this is the key number theory insight. Memorize: "count common factors of a and b" = "count divisors of gcd(a,b)". Divisor counting with a sqrt loop is O(sqrt(n)). Practice both GCD computation and divisor counting as building blocks — they combine frequently in number theory interview problems at Google, Meta, and Microsoft.

Similar Questions