VOOZH about

URL: https://www.geeksforgeeks.org/dsa/count-pairs-having-even-and-odd-lcm-from-an-array/

⇱ Count of pairs having even and odd LCM from an array - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Count of pairs having even and odd LCM from an array

Last Updated : 23 Jul, 2025

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:

  • Store the total count of pairs in a variable, say totalPairs. Initialize totalPairs as (N*(N - 1))/2.
  • Store the count of odd elements in the array in a variable, say cnt.
  • Store the count of pairs consisting of odd numbers only, in a variable, say odd. Therefore, odd = (cnt*(cnt - 1))/2.
  • After completing the above steps, print odd as the value of the count of pairs with odd LCM. Print (totalPairs - odd) as the count of pairs having even LCM.

Below is the implementation of the above approach.


Output: 
Even = 5, Odd = 1

 

Time Complexity: O(N)
Auxiliary Space: O(1)

Comment