![]() |
VOOZH | about |
Given two integer numbers, the task is to find count of all common divisors of given numbers?
Examples :
Input : a = 12, b = 24 Output: 6 // all common divisors are 1, 2, 3, // 4, 6 and 12 Input : a = 3, b = 17 Output: 1 // all common divisors are 1 Input : a = 20, b = 36 Output: 3 // all common divisors are 1, 2, 4
It is recommended to refer all divisors of a given number as a prerequisite of this article.
Naive Solution
A simple solution is to first find all divisors of first number and store them in an array or hash. Then find common divisors of second number and store them. Finally print common elements of two stored arrays or hash. The key is that the magnitude of powers of prime factors of a divisor should be equal to the minimum power of two prime factors of a and b.
Output:
6
Time Complexity: O(?n log n)
Auxiliary Space: O(n)
Efficient Solution -
A better solution is to calculate the greatest common divisor (gcd) of given two numbers, and then count divisors of that gcd.
Output :
6
Time complexity: O(n1/2) where n is the gcd of two numbers.
Auxiliary Space: O(1)
1. Define a function "gcd" that takes two integers "a" and "b" and returns their greatest common divisor (GCD) using the Euclidean algorithm.
2. Define a function "count_common_divisors" that takes two integers "a" and "b" and counts the number of common divisors of "a" and "b" using their GCD.
3. Calculate the GCD of "a" and "b" using the "gcd" function.
4. Initialize a counter "count" to 0.
5. Loop through all possible divisors of the GCD of "a" and "b" from 1 to the square root of the GCD.
6. If the current divisor divides the GCD evenly, increment the counter by 2 (because both "a" and "b" are divisible by the divisor).
7. If the square of the current divisor equals the GCD, decrement the counter by 1 (because we've already counted this divisor once).
8. Return the final count of common divisors.
9. In the main function, define two integers "a" and "b" and call the "count_common_divisors" function with these integers.
10. Print the number of common divisors of "a" and "b" using the printf function.
The number of common divisors of 12 and 18 is 4.
The time complexity of the gcd() function is O(log(min(a, b))), as it uses Euclid's algorithm which takes logarithmic time with respect to the smaller of the two numbers.
The time complexity of the count_common_divisors() function is O(sqrt(gcd(a, b))), as it iterates up to the square root of the gcd of the two numbers.
The space complexity of both functions is O(1), as they only use a constant amount of memory regardless of the input size.