![]() |
VOOZH | about |
Given an array arr[] of size N, the task is to count the number of pairs having even LCM and odd LCM.
Examples:
Input: arr[] = {3, 6, 5, 4}
Output: Even = 5, Odd = 1
Explanation: LCM of (3, 6) is 6, LCM of (3, 5) is 15, LCM of (3, 4) is 12, LCM of (6, 5) is 30, LCM of (6, 4) is 12, LCM of (5, 4) is 20.
Pairs having even LCM are (3, 6), (3, 4), (6, 5), (6, 4) and (5, 4).
Only pair having odd LCM is (3, 5).Input: arr[] = {4, 7, 2, 12}
Output: Even = 6, Odd = 0
Explanation: Pairs having even LCM = (4, 7), (4, 2), (4, 12), (7, 2), (7, 12), (2, 12).
No pair has odd LCM.
Naive Approach: The simplest approach is to generate all possible pairs to get all distinct pairs and for each pair, calculate their LCM. If their LCM is even, then increase the count of even. Otherwise, increase the count of odd. Finally, print their count separately.
Time Complexity: O((N2)*log(M)), where M is the smallest element in the array
Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is based on the fact that the LCM of 2 numbers is odd if and only if both the numbers are odd. Thus, find the total odd pairs in the array and to get a count of pairs with even LCM, subtract the count of odd pairs from the total number of possible pairs.
Follow the steps below to solve the problem:
Below is the implementation of the above approach.
Even = 5, Odd = 1
Time Complexity: O(N)
Auxiliary Space: O(1)