Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Hash
  • Practice Hash
  • MCQs on Hash
  • Hashing Tutorial
  • Hash Function
  • Index Mapping
  • Collision Resolution
  • Open Addressing
  • Separate Chaining
  • Quadratic probing
  • Double Hashing
  • Load Factor and Rehashing
  • Advantage & Disadvantage
Open In App
Next Article:
Count pairs from two arrays having sum equal to K
Next article icon

Count pairs from an array having GCD equal to the minimum element in the pair

Last Updated : 18 Oct, 2021
Comments
Improve
Suggest changes
Like Article
Like
Report

Given an array arr[] consisting of N integers, the task is to find the number of pairs such that the GCD of any pair of array elements is the minimum element of that pair.

Examples:

Input: arr[ ] = {2, 3, 1, 2}
Output: 4
Explanation:
Below are the all possible pairs from the given array:

  1. (0, 1): The GCD of the pair formed by element at indices 0 and 2 is gcd(2, 1) = 1, which is equal to its minimum value of the pair {2, 1}.
  2. (0, 3): The GCD of the pair formed by element at indices 0 and 3 is gcd(2, 2) = 2, which is equal to its minimum value of the pair {2, 2}.
  3. (1, 2): The GCD of the pair formed by taking element at indices 1 and 2 is gcd(3, 1) = 1, which is equal to its minimum value of the pair {3, 1}.
  4. (2, 3): The GCD of the pair formed by taking element at indices 2 and 3 is gcd(1, 2) = 1, which is equal to its minimum value of the pair {1, 2}.

Therefore, there is a total of 4 possible pairs whose GCD is equal to their minimum element of the pair.

Input: arr[] = {4, 6}
Output: 0

Naive Approach: The simplest approach to solve the given problem is to generate all possible pairs from the given array and if there exists any pair whose GCD is equal to the minimum elements of that pair, then count that pair. After checking for all the pairs, print the value of count obtained as the result.

Below is the implementation of the above approach:

C++
// C++ program for the above approach  #include <bits/stdc++.h> using namespace std;  // Function to count pairs from an // array having GCD equal to // minimum element of that pair int countPairs(int arr[], int N) {     // Stores the resultant count     int count = 0;      // Iterate over the range [0, N - 2]     for (int i = 0; i < N - 1; i++) {          // Iterate over the range [i + 1, N]         for (int j = i + 1; j < N; j++) {              // If arr[i] % arr[j] is 0             // or arr[j] % arr[i] is 0             if (arr[i] % arr[j] == 0                 || arr[j] % arr[i] == 0) {                  // Increment count by 1                 count++;             }         }     }      // Return the resultant count     return count; }  // Driver Code int main() {     int arr[] = { 2, 3, 1, 2 };     int N = sizeof(arr) / sizeof(arr[0]);     cout << countPairs(arr, N);      return 0; } 
Java
// java program for the above approach import java.io.*; import java.lang.*; import java.util.*;  public class GFG {      // Function to count pairs from an     // array having GCD equal to     // minimum element of that pair     static int countPairs(int arr[], int N)     {                // Stores the resultant count         int count = 0;          // Iterate over the range [0, N - 2]         for (int i = 0; i < N - 1; i++) {              // Iterate over the range [i + 1, N]             for (int j = i + 1; j < N; j++) {                  // If arr[i] % arr[j] is 0                 // or arr[j] % arr[i] is 0                 if (arr[i] % arr[j] == 0                     || arr[j] % arr[i] == 0) {                      // Increment count by 1                     count++;                 }             }         }          // Return the resultant count         return count;     }      // Driver Code     public static void main(String[] args)     {          int arr[] = { 2, 3, 1, 2 };         int N = arr.length;         System.out.print(countPairs(arr, N));     } }  // This code is contributed by Kingash. 
Python3
# Python3 program for the above approach  # Function to count pairs from an # array having GCD equal to # minimum element of that pair def countPairs(arr, N):        # Stores the resultant count     count = 0      # Iterate over the range [0, N - 2]     for i in range(N - 1):                # Iterate over the range [i + 1, N]         for j in range(i + 1, N):                        # If arr[i] % arr[j] is 0             # or arr[j] % arr[i] is 0             if (arr[i] % arr[j] == 0 or arr[j] % arr[i] == 0):                                  # Increment count by 1                 count += 1                       # Return the resultant count     return count  # Driver Code if __name__ == '__main__':     arr = [2, 3, 1, 2]     N = len(arr)     print (countPairs(arr, N))  # This code is contributed by mohit kumar 29. 
C#
// C# program for the above approach  using System;  public class GFG {      // Function to count pairs from an     // array having GCD equal to     // minimum element of that pair     static int countPairs(int[] arr, int N)     {          // Stores the resultant count         int count = 0;          // Iterate over the range [0, N - 2]         for (int i = 0; i < N - 1; i++) {              // Iterate over the range [i + 1, N]             for (int j = i + 1; j < N; j++) {                  // If arr[i] % arr[j] is 0                 // or arr[j] % arr[i] is 0                 if (arr[i] % arr[j] == 0                     || arr[j] % arr[i] == 0) {                      // Increment count by 1                     count++;                 }             }         }          // Return the resultant count         return count;     }      // Driver Code     public static void Main(string[] args)     {          int[] arr = { 2, 3, 1, 2 };         int N = arr.Length;         Console.WriteLine(countPairs(arr, N));     } }  // This code is contributed by ukasp. 
JavaScript
<script> // Javascript implementation of the above approach      // Function to count pairs from an     // array having GCD equal to     // minimum element of that pair     function countPairs(arr, N)     {                // Stores the resultant count         let count = 0;          // Iterate over the range [0, N - 2]         for (let i = 0; i < N - 1; i++) {              // Iterate over the range [i + 1, N]             for (let j = i + 1; j < N; j++) {                  // If arr[i] % arr[j] is 0                 // or arr[j] % arr[i] is 0                 if (arr[i] % arr[j] == 0                     || arr[j] % arr[i] == 0) {                      // Increment count by 1                     count++;                 }             }         }          // Return the resultant count         return count;     }     // Driver Code           let arr = [ 2, 3, 1, 2 ];         let N = arr.length;         document.write(countPairs(arr, N));        </script> 

Output: 
4

 

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

Efficient Approach: The above approach can be optimized based on the following observations:

  • The minimum element of the pair should divide the maximum element of the pair, and it can be observed that element 1 can form a total of (N - 1) pairs.
  • Every element can form ^YC_2           pair with itself where Y is the count of an array element.
  • The idea is to traverse over the divisors of every array element and increment the count of pairs that can be formed by the frequencies of the divisors.

Follow the steps below to solve the problem:

  • Initialize a variable, say res, that stores the resultant count.
  • Initialize a map, say mp, that stores the count of every array element.
  • Traverse the array arr[] and increment the count of arr[i] in mp.
  • Iterate over the pairs of map mp and perform the following operations:
    • Store the value of array element in a variable say X and frequency of that number in a variable Y.
    • If the value of X is 1, then increment the value of res by (N - 1) and continue.
    • Increment the value of res by (Y*(Y - 1))/2.
    • Now, iterate over the divisors of the integer X using a variable j and increment the res by mp[j].
  • After completing the above steps, print the value of res as the total count obtained.

Below is the implementation of the above approach:

C++
// C++ program for the above approach  #include <bits/stdc++.h> using namespace std;  // Function to count pairs from an // array having GCD equal to // minimum element of that pair int CountPairs(int arr[], int N) {     // Stores the resultant count     int res = 0;      // Stores the frequency of     // each array element     map<int, int> mp;      // Traverse the array arr[]     for (int i = 0; i < N; i++) {         mp[arr[i]]++;     }     // Iterate over the Map mp     for (auto p : mp) {          // Stores the array element         int x = p.first;          // Stores the count         // of array element x         int y = p.second;          // If x is 1         if (x == 1) {              // Increment res by N-1             res += N - 1;             continue;         }          // Increment res by yC2         res += (y * (y - 1)) / 2;          // Iterate over the         // range [2, sqrt(x)]         for (int j = 2;              j <= sqrt(x); j++) {              // If x is divisible by j             if (x % j == 0) {                  // Increment the value                 // of res by mp[j]                 res += mp[j];                  // If j is not equal to x/j                 if (j != x / j)                      // Increment res                     // by mp[x/j]                     res += mp[x / j];             }         }     }      // Return the resultant count     return res; }  // Driver Code int main() {     int arr[] = { 2, 3, 1, 2 };     int N = sizeof(arr) / sizeof(arr[0]);     cout << CountPairs(arr, N);      return 0; } 
Java
// Java program for the above approach import java.io.*; import java.util.*;  class GFG {          // Function to count pairs from an     // array having GCD equal to     // minimum element of that pair     static int CountPairs(int arr[], int N)     {                // Stores the resultant count         int res = 0;          // Stores the frequency of         // each array element         Map<Integer, Integer> mp = new HashMap<>();          // Traverse the array arr[]         for (int i = 0; i < N; i++) {               Integer c = mp.get(arr[i]);             mp.put(arr[i], (c == null) ? 1 : c + 1);         }         // Iterate over the Map mp           Iterator<Map.Entry<Integer, Integer>> itr = mp.entrySet().iterator();                   while(itr.hasNext())         {              Map.Entry<Integer, Integer> entry = itr.next();                       // Stores the array element             int x = (int)entry.getKey();              // Stores the count             // of array element x             int y = (int)entry.getValue();              // If x is 1             if (x == 1) {                  // Increment res by N-1                 res += N - 1;                 continue;             }              // Increment res by yC2             res += (y * (y - 1)) / 2;              // Iterate over the             // range [2, sqrt(x)]             for (int j = 2; j <= Math.sqrt(x); j++) {                  // If x is divisible by j                 if (x % j == 0) {                      // Increment the value                     // of res by mp[j]                     res += mp.get(j);                      // If j is not equal to x/j                     if (j != x / j)                          // Increment res                         // by mp[x/j]                         res += mp.get((int)x / j);                 }             }         }          // Return the resultant count         return res;     }      // Driver Code     public static void main (String[] args) {         int arr[] = { 2, 3, 1, 2 };         int N = arr.length;         System.out.println(CountPairs(arr, N));     } }  // This code is contributed by Dharanendra L V. 
Python3
# Python3 program for the above approach from math import sqrt  # Function to count pairs from an # array having GCD equal to # minimum element of that pair def CountPairs(arr, N):          # Stores the resultant count     res = 0      # Stores the frequency of     # each array element     mp = {}      # Traverse the array arr[]     for i in range(N):         if (arr[i] in mp):             mp[arr[i]] += 1         else:             mp[arr[i]] = 1                  # Iterate over the Map mp     for key, value in mp.items():                  # Stores the array element         x = key          # Stores the count         # of array element x         y = value          # If x is 1         if (x == 1):              # Increment res by N-1             res += N - 1             continue          # Increment res by yC2         res += (y * (y - 1)) // 2          # Iterate over the         # range [2, sqrt(x)]         for j in range(2, int(sqrt(x)) + 1, 1):              # If x is divisible by j             if (x % j == 0):                  # Increment the value                 # of res by mp[j]                 res += mp[j]                  # If j is not equal to x/j                 if (j != x // j):                      # Increment res                     # by mp[x/j]                     res += mp[x // j]      # Return the resultant count     return res  # Driver Code if __name__ == '__main__':          arr = [ 2, 3, 1, 2 ]     N = len(arr)          print(CountPairs(arr, N))  # This code is contributed by SURENDRA_GANGWAR 
C#
// C# program for the above approach using System; using System.Collections.Generic;  class GFG{  // Function to count pairs from an // array having GCD equal to // minimum element of that pair static int CountPairs(int []arr, int N) {          // Stores the resultant count     int res = 0;      // Stores the frequency of     // each array element     Dictionary<int,                int> mp = new Dictionary<int,                                         int>();      // Traverse the array arr[]     for(int i = 0; i < N; i++)     {         if (mp.ContainsKey(arr[i]))             mp[arr[i]]++;         else             mp.Add(arr[i], 1);     }          // Iterate over the Map mp     foreach(KeyValuePair<int, int> kvp in mp)     {          // Stores the array element         int x = kvp.Key;          // Stores the count         // of array element x         int y = kvp.Value;          // If x is 1         if (x == 1)          {                          // Increment res by N-1             res += N - 1;             continue;         }          // Increment res by yC2         res += (y * (y - 1)) / 2;          // Iterate over the         // range [2, sqrt(x)]         for(int j = 2;                 j <= Math.Sqrt(x); j++)         {              // If x is divisible by j             if (x % j == 0)              {                  // Increment the value                 // of res by mp[j]                 res += mp[j];                  // If j is not equal to x/j                 if (j != x / j)                      // Increment res                     // by mp[x/j]                     res += mp[x / j];             }         }     }      // Return the resultant count     return res; }  // Driver Code public static void Main() {     int []arr = { 2, 3, 1, 2 };     int N = arr.Length;          Console.Write(CountPairs(arr, N)); } }  // This code is contributed by bgangwar59 
JavaScript
<script>  // Javascript program for the above approach  // Function to count pairs from an // array having GCD equal to // minimum element of that pair function CountPairs(arr, N) {     // Stores the resultant count     var res = 0;      // Stores the frequency of     // each array element     var mp = new Map();      // Traverse the array arr[]     for (var i = 0; i < N; i++) {         if(mp.has(arr[i]))         {             mp.set(arr[i], mp.get(arr[i])+1);         }         else{             mp.set(arr[i], 1);         }     }     // Iterate over the Map mp     mp.forEach((value, key) => {          // Stores the array element         var x = key;          // Stores the count         // of array element x         var y = value;          // If x is 1         if (x == 1) {              // Increment res by N-1             res += N - 1;         }          // Increment res by yC2         res += parseInt((y * (y - 1)) / 2);          // Iterate over the         // range [2, sqrt(x)]         for (var j = 2;              j <= parseInt(Math.sqrt(x)); j++) {              // If x is divisible by j             if (x % j == 0) {                  // Increment the value                 // of res by mp[j]                 res += mp.get(j);                  // If j is not equal to x/j                 if (j != parseInt(x / j))                      // Increment res                     // by mp[x/j]                     res += mp.get(parseInt(x / j));             }         }     });        // Return the resultant count     return res; }  // Driver Code var arr = [2, 3, 1, 2 ]; var N = arr.length; document.write( CountPairs(arr, N));  </script> 

Output: 
4

 

Time Complexity: O(N*?M), where M is the maximum element of the array.
Auxiliary Space: O(1)


Next Article
Count pairs from two arrays having sum equal to K
author
santhoshcharan
Improve
Article Tags :
  • Mathematical
  • Hash
  • DSA
  • Arrays
  • cpp-map
  • frequency-counting
Practice Tags :
  • Arrays
  • Hash
  • Mathematical

Similar Reads

  • Count of pairs having each element equal to index of the other from an Array
    Given an integer N and an array arr[] that contains elements in the range [1, N], the task is to find the count of all pairs (arr[i], arr[j]) such that i < j and i == arr[j] and j == arr[i]. Examples: Input: N = 4, arr[] = {2, 1, 4, 3} Output: 2 Explanation: All possible pairs are {1, 2} and {3,
    6 min read
  • Check if array can be sorted by swapping pairs having GCD equal to the smallest element in the array
    Given an array arr[] of size N, the task is to check if an array can be sorted by swapping only the elements whose GCD (greatest common divisor) is equal to the smallest element of the array. Print “Yes” if it is possible to sort the array. Otherwise, print “No”. Examples: Input: arr[] = {4, 3, 6, 6
    11 min read
  • Count pairs from two arrays having sum equal to K
    Given an integer K and two arrays A1 and A2, the task is to return the total number of pairs (one element from A1 and one element from A2) with a sum equal to K. Note: Arrays can have duplicate elements. We consider every pair as different, the only constraint is, an element (of any array) can parti
    6 min read
  • Choose atleast two elements from array such that their GCD is 1 and cost is minimum
    Given two integer arrays arr[] and cost[] where cost[i] is the cost of choosing arr[i]. The task is to choose a subset with at least two elements such that the GCD of all the elements from the subset is 1 and the cost of choosing those elements is as minimum as possible then print the minimum cost.
    6 min read
  • Rearrange array to make it non-decreasing by swapping pairs having GCD equal to minimum array element
    Given an array, arr[] consisting of N positive integers, the task is to make the array non-decreasing by swapping pairs (arr[i], arr[j]) such that i != j (1 ≤ i, j ≤ n) and GCD(arr[i], arr[j]) is equal to the minimum element present in the array. Examples: Input: arr[] = {4, 3, 6, 6, 2, 9}Output: Ye
    6 min read
  • Number of Good Pairs - Count of index pairs with equal values in an array
    Given an array of n elements. The task is to count the total number of indices (i, j) such that arr[i] = arr[j] and i < j Examples : Input: arr = [5, 2, 3, 5, 5, 3]Output: 4Explanation: There are 4 good pairs (0, 3), (0, 4), (3, 4), (2, 5) Input: arr = [1, 1, 1, 1]Output: 6Explanation: All 6 pair
    7 min read
  • Count pairs from an array having equal sum and quotient
    Given an array arr[] consisting of N integers, the task is to count the number of valid pairs (i, j) such that arr[i] + arr[j] = arr[i] / arr[j]. Examples: Input: arr[] = {-4, -3, 0, 2, 1}Output: 1Explanation: The only possible pair is (0, 3) which satisfies the condition ( -4 + 2 = -4 / 2 (= -2) ).
    10 min read
  • Count unequal element pairs from the given Array
    Given an array arr[] of N elements. The task is to count the total number of indices (i, j) such that arr[i] != arr[j] and i < j.Examples: Input: arr[] = {1, 1, 2} Output: 2 (1, 2) and (1, 2) are the only valid pairs.Input: arr[] = {1, 2, 3} Output: 3Input: arr[] = {1, 1, 1} Output: 0 Recommended
    10 min read
  • Minimum deletions required to make GCD of the array equal to 1
    Given an array arr[] of N integers, the task is to find the minimum deletions required to make the GCD of the resulting array elements equal to 1. If it is impossible then print -1.Examples: Input: arr[] = {2, 4, 6, 3} Output: 0 It is clear that GCD(2, 4, 6, 3) = 1 So, we do not need to delete any e
    5 min read
  • Maximize count of distinct elements possible in an Array from the given operation
    Given an array A[] of size N, the task is to maximize the count of distinct elements in the array by inserting the absolute differences of the existing array elements. Examples: Input: A[] = {1, 2, 3, 5} Output: 5 Explanation: Possible absolute differences among the array elements are: (2 - 1) = 1 (
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences