![]() |
VOOZH | about |
We need to find number of possible pairs (a, b) such that GCD(a, b) is equal to given G and LCM (a, b) such that LCM(a, b) is equal to given L.
Examples:
Input : G = 2, L = 12 Output : 4 Explanation : There are 4 possible pairs : (2, 12), (4, 6), (6, 4), (12, 2)
Input : G = 3, L = 6 Output : 2 Explanation : There are 2 possible pairs : (3, 6), (6, 3)
Solution 1 (Simple):
Since a and b both will be less than or equal to lcm(a, b) L, so we try all possible pairs that have product equal to L * G. Note that product of a and b is same as product of gcd(a, b) and lcm(a, b), a*b = G*L.
Here is our algorithm
p = G*L count = 0 for a = 1 to L if p%a == 0 and gcd(a, p/a) = G count++ end if end for return count
Total possible pair with GCD 2 & LCM 12 = 4
Auxiliary Space : O(1)
Time Complexity: O( L * log(L) ). We have one for loop which iterates L times and in each iteration in the worst case, gcd will be called so O(log L) in the worst case for that call.
Solution 2 (Efficient):
We know that G * L = a * b Since G is gcd(a, b), both a and b will have G as its factor Let A = a/G Let B = b/G From above definitions of A and B, GCD of A and B must be 1. We can write, a = G * A, b = G * B G * L = G * A * G * B A * B = L / G Now, we need to find all possible pairs of (A, B) such that gcd(A, B) = 1 and A*B = L/G Let say p1, p2, ..., pk are prime factors of L/G. Then if p1 is present in prime factorization of A then p1 can't be present in prime factorization of B because gcd(A, B) = 1. Therefore each prime factor pi will be present in either A or B. Hence total possible ways to divide all prime factors among A and B is 2^k, where L/G has k distinct prime factors.
Below is implementation of above steps.
Output:
Total possible pair with GCD 2 & LCM 12 = 4
Analysis of above algorithm
Auxiliary Space: O(1)
Time Complexity : O(sqrt(L/G) * log(L/G)). For time complexity to find number of distinct prime factors we need O(sqrt(L/G) * log (L/G)) time, Here sqrt(L) iterations are there in the worst case and in each iteration O(log L/G) iterations again.