Number of pairs such that their HCF and LCM is equal

Given an array a[] of non-negative integers. The task is to count the number of pairs (i, j) in the array such that LCM(a[i], a[j]) = HCF(a[i], a[j]).

Note: The pair (i, j) and (j, i) are considered same and i should not be equal to j.

Examples:

Input : a[] = {3, 4, 3, 4, 5}
Output : 2
Pairs are (3, 3) and (4, 4)

Input  : a[] = {1, 1, 1}
Output : 3

Naive approach: Generate all possible pairs and count pairs with equal HCF and LCM.

C++



filter_none

edit
close

play_arrow

link
brightness_4
code

// Naive C++ program to count number of pairs
// such that their hcf and lcm are equal
#include <bits/stdc++.h>
using namespace std;
  
// Function to return HCF of two numbers
int gcd(int a, int b)
{
    if (a == 0)
        return b;
    return gcd(b % a, a);
}
  
// Function to return LCM of two numbers
int lcm(int a, int b)
{
    return (a * b) / gcd(a, b);
}
  
// Returns the number of valid pairs
int countPairs(int arr[], int n)
{
    int ans = 0; // initializing answer
  
    // Traversing the array. For each array
    // element, checking if it
    // follow the condition
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
            if (lcm(arr[i], arr[j]) == gcd(arr[i], arr[j]))
                ans++;
    return ans;
}
  
// Driver function
int main()
{
    int arr[] = { 1, 1, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << countPairs(arr, n);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Naive Java program to count number of pairs
// such that their hcf and lcm are equal
import java.util.*;
  
class GFG{
   
// Function to return HCF of two numbers
static int gcd(int a, int b)
{
    if (a == 0)
        return b;
    return gcd(b % a, a);
}
   
// Function to return LCM of two numbers
static int lcm(int a, int b)
{
    return (a * b) / gcd(a, b);
}
   
// Returns the number of valid pairs
static int countPairs(int arr[], int n)
{
    int ans = 0; // initializing answer
   
    // Traversing the array. For each array
    // element, checking if it
    // follow the condition
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
            if (lcm(arr[i], arr[j]) == gcd(arr[i], arr[j]))
                ans++;
    return ans;
}
   
// Driver function
public static void main(String[] args)
{
    int arr[] = { 1, 1, 1 };
    int n = arr.length;
    System.out.print(countPairs(arr, n));
}
}
  
// This code is contributed by Rajput-Ji

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Naive Python program to count number of pairs
# such that their hcf and lcm are equal
  
# Function to return HCF of two numbers
def gcd(a, b):
    if (a == 0):
        return b;
    return gcd(b % a, a);
  
# Function to return LCM of two numbers
def lcm(a, b):
    return (a * b) / gcd(a, b);
  
# Returns the number of valid pairs
def countPairs(arr, n):
    ans = 0; # initializing answer
  
    # Traversing the array. For each array
    # element, checking if it
    # follow the condition
    for i in range(n):
        for j in range(i+1,n):
            if (lcm(arr[i], arr[j]) == gcd(arr[i], arr[j])):
                ans+=1;
    return ans;
  
# Driver function
if __name__ == '__main__':
    arr = [ 1, 1, 1 ];
    n = len(arr);
    print(countPairs(arr, n));
  
# This code is contributed by 29AjayKumar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// Naive C# program to count number of pairs
// such that their hcf and lcm are equal
using System;
  
class GFG{
    
// Function to return HCF of two numbers
static int gcd(int a, int b)
{
    if (a == 0)
        return b;
    return gcd(b % a, a);
}
    
// Function to return LCM of two numbers
static int lcm(int a, int b)
{
    return (a * b) / gcd(a, b);
}
    
// Returns the number of valid pairs
static int countPairs(int []arr, int n)
{
    int ans = 0; // initializing answer
    
    // Traversing the array. For each array
    // element, checking if it
    // follow the condition
    for (int i = 0; i < n; i++)
        for (int j = i + 1; j < n; j++)
            if (lcm(arr[i], arr[j]) == gcd(arr[i], arr[j]))
                ans++;
    return ans;
}
    
// Driver function
public static void Main(String[] args)
{
    int []arr = { 1, 1, 1 };
    int n = arr.Length;
    Console.Write(countPairs(arr, n));
}
}
  
// This code is contributed by 29AjayKumar

chevron_right


Output:

3

Efficient Approach: If we observe carefully, it can be proved that the HCF and LCM of two numbers can be equal only when the numbers are also equal.

Proof:

Let,
HCF(a[i], a[j]) = LCM(a[i], a[j]) = K

Since HCF(a[i], a[j]) = k,
a[i] = k*n1, a[j] = k*n2, for some natural numbers n1, n2

We know that,
HCF × LCM = Product of the two numbers

Therefore,
k*k = k*n1 × k*n2
or, n1*n2 = 1

Implies, n1 = n2 = 1, since n1, n2 are natural numbers.

Therefore,
a[i] = k*n1 = k, a[j] = k*n2 = k
i.e. the numbers must be equal.

So we have to count pairs wih same elements in the pair.

It is observed that only the pairs of the form (arr[i], arr[j]) where arr[i] = arr[j] will satisfy the given condition. So, the problem now gets reduced to finding the number of pairs (arr[i], arr[j]) such that arr[i] = arr[j].

Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

   
  
// C++ program to count number of pairs
// such that their hcf and lcm are equal
#include <bits/stdc++.h>
using namespace std;
  
// Function to count number of pairs
// such that their hcf and lcm are equal
int countPairs(int a[], int n)
{
    // Store frequencies of array elements
    unordered_map<int, int> frequency;
    for (int i = 0; i < n; i++) {
        frequency[a[i]]++;
    }
  
    int count = 0;
  
    // Count of pairs (arr[i], arr[j])
    // where arr[i] = arr[j]
    for (auto x : frequency) {
        int f = x.second;
        count += f * (f - 1) / 2;
    }
  
    // Count of pairs (arr[i], arr[j]) where
    // arr[i] = arr[j],
    return count;
}
  
// Driver function
int main()
{
    int arr[] = { 1, 1, 1 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << countPairs(arr, n);
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to count number of pairs
// such that their hcf and lcm are equal
  
import java.util.*;
  
class GFG{
   
// Function to count number of pairs
// such that their hcf and lcm are equal
static int countPairs(int arr[], int n)
{
    // Store frequencies of array elements
    HashMap<Integer,Integer> frequency =
            new HashMap<Integer,Integer>();
    for (int i = 0; i < n; i++) {
        if(frequency.containsKey(arr[i])){
            frequency.put(arr[i], frequency.get(arr[i])+1);
        }else{
            frequency.put(arr[i], 1);
    }
    }
   
    int count = 0;
   
    // Count of pairs (arr[i], arr[j])
    // where arr[i] = arr[j]
    for (Map.Entry<Integer,Integer> x : frequency.entrySet()) {
        int f = x.getValue();
        count += f * (f - 1) / 2;
    }
   
    // Count of pairs (arr[i], arr[j]) where
    // arr[i] = arr[j],
    return count;
}
   
// Driver function
public static void main(String[] args)
{
    int arr[] = { 1, 1, 1 };
    int n = arr.length;
    System.out.print(countPairs(arr, n));
}
}
  
// This code contributed by sapnasingh4991

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to count number of pairs
// such that their hcf and lcm are equal
using System;
using System.Collections.Generic;
  
class GFG{
  
// Function to count number of pairs
// such that their hcf and lcm are equal
static int countPairs(int []a, int n)
{
    // Store frequencies of array elements
    Dictionary<int, int> frequency = new Dictionary<int,int>();
        for (int i = 0; i < n; i++) 
        
            if (frequency.ContainsKey(a[i]))  
            
                var val = frequency[a[i]]; 
                frequency.Remove(a[i]); 
                frequency.Add(a[i], val + 1);  
            }  
            else
            
                frequency.Add(a[i], 1); 
            
        
           
    int count = 0;
  
    // Count of pairs (arr[i], arr[j])
    // where arr[i] = arr[j]
    foreach(KeyValuePair<int, int> entry in frequency) {
        int f = entry.Value;
        count += f * (f - 1) / 2;
    }
  
    // Count of pairs (arr[i], arr[j]) where
    // arr[i] = arr[j],
    return count;
}
  
// Driver function
public static void Main(String[] args)
{
    int []arr = { 1, 1, 1 };
    int n = arr.Length;
    Console.Write(countPairs(arr, n));
}
}
  
// This code is contributed by shivanisinghss2110

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python 3 program to count number of pairs
# such that their hcf and lcm are equal
from collections import defaultdict
   
# Function to count number of pairs
# such that their hcf and lcm are equal
def countPairs(a, n):
  
    # Store frequencies of array elements
    frequency = defaultdict(int)
    for i in range(n) :
        frequency[a[i]] += 1
      
   
    count = 0
   
    # Count of pairs (arr[i], arr[j])
    # where arr[i] = arr[j]
    for x in frequency.keys():
        f = frequency[x]
        count += f * (f - 1) // 2
   
    # Count of pairs (arr[i], arr[j]) where
    # arr[i] = arr[j],
    return count
   
# Driver function
if __name__ == "__main__":
      
    arr = [ 1, 1, 1 ]
    n = len(arr)
    print(countPairs(arr, n))
  
# This code is contributed by chitranayal

chevron_right


Output:

3

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Article Tags :
Practice Tags :


2


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.