Program to count number of common divisors of two numbers in Python

When working with two numbers, we often need to find how many positive integers divide both numbers evenly. These are called common divisors. A key insight is that all common divisors of two numbers are also divisors of their GCD (Greatest Common Divisor).

So, if the input is like a = 288 and b = 240, then the output will be 10 because the common divisors are [1, 2, 3, 4, 6, 8, 12, 16, 24, 48].

Algorithm

To solve this problem, we follow these steps ?

  • Find the GCD of both numbers
  • Count all divisors of the GCD
  • Return the count

Method 1: Using GCD Range

We iterate from 1 to GCD and check which numbers divide both original numbers ?

from math import gcd

def count_common_divisors(a, b):
    result = 0
    gcd_value = gcd(a, b)
    
    for i in range(1, gcd_value + 1):
        if (a % i) == 0 and (b % i) == 0:
            result += 1
    
    return result

a, b = 288, 240
print(f"Common divisors of {a} and {b}: {count_common_divisors(a, b)}")
Common divisors of 288 and 240: 10

Method 2: Optimized Approach

A more efficient approach counts divisors of the GCD directly ?

from math import gcd

def count_common_divisors_optimized(a, b):
    gcd_value = gcd(a, b)
    count = 0
    
    # Count divisors of GCD
    for i in range(1, int(gcd_value**0.5) + 1):
        if gcd_value % i == 0:
            count += 1
            # If i is not the square root, count its pair
            if i != gcd_value // i:
                count += 1
    
    return count

a, b = 288, 240
print(f"Common divisors of {a} and {b}: {count_common_divisors_optimized(a, b)}")

# Let's also display the actual common divisors
gcd_value = gcd(a, b)
divisors = []
for i in range(1, gcd_value + 1):
    if gcd_value % i == 0:
        divisors.append(i)

print(f"The common divisors are: {divisors}")
Common divisors of 288 and 240: 10
The common divisors are: [1, 2, 3, 4, 6, 8, 12, 16, 24, 48]

Comparison

Method Time Complexity Space Complexity Best For
GCD Range O(GCD(a,b)) O(1) Simple implementation
Optimized O(?GCD(a,b)) O(1) Large numbers

Conclusion

The key insight is that common divisors of two numbers are exactly the divisors of their GCD. Use the optimized approach for better performance with large numbers.

Updated on: 2026-03-26T15:47:25+05:30

694 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements