#2427

Number of Common Factors

Easy
MathEnumerationNumber TheoryMathEnumeration
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(sqrt(n))
Space
O(1)
O(1)
💡

Intuition

Time O(sqrt(n))Space O(1)

Instead of checking every number, we can find the greatest common divisor (GCD) of a and b, and then count the factors of the GCD. This is more efficient.

⚙️

Algorithm

6 steps
  1. 1Step 1: Calculate the GCD of a and b.
  2. 2Step 2: Initialize a counter to zero.
  3. 3Step 3: Loop through all integers from 1 to the square root of the GCD.
  4. 4Step 4: For each integer, check if it divides the GCD.
  5. 5Step 5: If it does, increment the counter. If the division results in a different integer, increment the counter again.
  6. 6Step 6: Return the counter as the number of common factors.
solution.py11 lines
1import math
2
3def commonFactors(a, b):
4    gcd_ab = math.gcd(a, b)
5    count = 0
6    for i in range(1, int(gcd_ab**0.5) + 1):
7        if gcd_ab % i == 0:
8            count += 1
9            if i != gcd_ab // i:
10                count += 1
11    return count

Complexity note: The time complexity is O(sqrt(n)) because we only check up to the square root of the GCD to find factors. The space complexity is O(1) since we only use a few variables.

  • 1Understanding GCD can simplify the problem significantly.
  • 2Counting factors can be optimized by checking up to the square root.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.