Find the number of pairs such that their gcd is equals to 1 - GeeksforGeeks

18 Mar, 2022
Given an array a of size N. The task is to find the number of pairs such that gcd(a[i], a[j]) is equal to 1, where 1 ≤ i < j ≤ N. 
Examples:  
Input : a[] = {1, 2, 4, 6} Output : 3 {1, 2}, {1, 4}, {1, 6} are such pairs
Input : a[] = {1, 2, 3, 4, 5, 6} Output : 11  
Approach : The answer is to sum of μ(X) * C(D(X), 2) overall integer X. Where, μ(X) is Mobius function, C(N, K) is the selection of K things from N and D(X) is the number of integers in the given sequence that are divisible by X.The correctness of the solution follows from the fact that we can do an inclusion-exclusion principle solution and to show that it is, in fact, equal to our answer. That means that we will add to the answer the number of pairs that are divisible by some intermediate (in the IEP) product D if D is formed by multiplication of even number of prime numbers and subtract this number of pairs otherwise. 
So, we get: 
1 for addition, because that is Möbius function for square-free numbers with even number of prime divisors.
-1 for subtraction, that is Mobius function for square-free numbers with an odd number of prime divisors.
0 for square-free numbers. By the definition, they can’t occur in our IEP solution.
Below is the implementation of the above approach :  
C++
Java
Python3
C#
Javascript
// CPP program to find the number of pairs// such that gcd equals to 1#include <bits/stdc++.h>using namespace std; #define N 100050 int lpf[N], mobius[N]; // Function to calculate least// prime factor of each numbervoid least_prime_factor(){    for (int i = 2; i < N; i++)         // If it is a prime number        if (!lpf[i])             for (int j = i; j < N; j += i)                 // For all multiples which are not                // visited yet.                if (!lpf[j])                    lpf[j] = i;} // Function to find the value of Mobius function// for all the numbers from 1 to nvoid Mobius(){    for (int i = 1; i < N; i++) {         // If number is one        if (i == 1)            mobius[i] = 1;        else {             // If number has a squared prime factor            if (lpf[i / lpf[i]] == lpf[i])                mobius[i] = 0;             // Multiply -1 with the previous number            else                mobius[i] = -1 * mobius[i / lpf[i]];        }    }} // Function to find the number of pairs// such that gcd equals to 1int gcd_pairs(int a[], int n){    // To store maximum number    int maxi = 0;     // To store frequency of each number    int fre[N] = { 0 };     // Find frequency and maximum number    for (int i = 0; i < n; i++) {        fre[a[i]]++;        maxi = max(a[i], maxi);    }     least_prime_factor();    Mobius();     // To store number of pairs with gcd equals to 1    int ans = 0;     // Traverse through the all possible elements    for (int i = 1; i <= maxi; i++) {        if (!mobius[i])            continue;         int temp = 0;        for (int j = i; j <= maxi; j += i)            temp += fre[j];         ans += temp * (temp - 1) / 2 * mobius[i];    }     // Return the number of pairs    return ans;} // Driver codeint main(){    int a[] = { 1, 2, 3, 4, 5, 6 };     int n = sizeof(a) / sizeof(a[0]);     // Function call    cout << gcd_pairs(a, n);     return 0;}
// Java program to find the number of pairs// such that gcd equals to 1class GFG{ static int N = 100050; static int []lpf = new int[N];static int []mobius = new int[N]; // Function to calculate least// prime factor of each numberstatic void least_prime_factor(){    for (int i = 2; i < N; i++)         // If it is a prime number        if (lpf[i] == 0)             for (int j = i; j < N; j += i)                 // For all multiples which are not                // visited yet.                if (lpf[j] == 0)                    lpf[j] = i;} // Function to find the value of Mobius function// for all the numbers from 1 to nstatic void Mobius(){    for (int i = 1; i < N; i++)    {         // If number is one        if (i == 1)            mobius[i] = 1;        else        {             // If number has a squared prime factor            if (lpf[i / lpf[i]] == lpf[i])                mobius[i] = 0;             // Multiply -1 with the previous number            else                mobius[i] = -1 * mobius[i / lpf[i]];        }    }} // Function to find the number of pairs// such that gcd equals to 1static int gcd_pairs(int a[], int n){    // To store maximum number    int maxi = 0;     // To store frequency of each number    int []fre = new int[N];     // Find frequency and maximum number    for (int i = 0; i < n; i++)    {        fre[a[i]]++;        maxi = Math.max(a[i], maxi);    }     least_prime_factor();    Mobius();     // To store number of pairs with gcd equals to 1    int ans = 0;     // Traverse through the all possible elements    for (int i = 1; i <= maxi; i++)    {        if (mobius[i] == 0)            continue;         int temp = 0;        for (int j = i; j <= maxi; j += i)            temp += fre[j];         ans += temp * (temp - 1) / 2 * mobius[i];    }     // Return the number of pairs    return ans;} // Driver codepublic static void main (String[] args){    int a[] = { 1, 2, 3, 4, 5, 6 };     int n = a.length;     // Function call    System.out.print(gcd_pairs(a, n));}} // This code is contributed by PrinciRaj1992
# Python3 program to find the number of pairs# such that gcd equals to 1N = 100050 lpf = [0 for i in range(N)]mobius = [0 for i in range(N)] # Function to calculate least# prime factor of each numberdef least_prime_factor():     for i in range(2, N):         # If it is a prime number        if (lpf[i] == 0):             for j in range(i, N, i):                 # For all multiples which are not                # visited yet.                if (lpf[j] == 0):                    lpf[j] = i # Function to find the value of Mobius function# for all the numbers from 1 to ndef Mobius():     for i in range(1, N):         # If number is one        if (i == 1):            mobius[i] = 1        else:             # If number has a squared prime factor            if (lpf[ (i // lpf[i]) ] == lpf[i]):                mobius[i] = 0             # Multiply -1 with the previous number            else:                mobius[i] = -1 * mobius[i // lpf[i]] # Function to find the number of pairs# such that gcd equals to 1def gcd_pairs(a, n):     # To store maximum number    maxi = 0     # To store frequency of each number    fre = [0 for i in range(N)]     # Find frequency and maximum number    for i in range(n):        fre[a[i]] += 1        maxi = max(a[i], maxi)     least_prime_factor()    Mobius()     # To store number of pairs with gcd equals to 1    ans = 0     # Traverse through the all possible elements    for i in range(1, maxi + 1):        if (mobius[i] == 0):            continue         temp = 0        for j in range(i, maxi + 1, i):            temp += fre[j]         ans += temp * (temp - 1) // 2 * mobius[i]     # Return the number of pairs    return ans # Driver codea = [1, 2, 3, 4, 5, 6] n = len(a) # Function callprint(gcd_pairs(a, n)) # This code is contributed by Mohit Kumar
// C# program to find the number of pairs// such that gcd equals to 1using System; class GFG{static int N = 100050; static int []lpf = new int[N];static int []mobius = new int[N]; // Function to calculate least// prime factor of each numberstatic void least_prime_factor(){    for (int i = 2; i < N; i++)         // If it is a prime number        if (lpf[i] == 0)             for (int j = i; j < N; j += i)                 // For all multiples which are not                // visited yet.                if (lpf[j] == 0)                    lpf[j] = i;} // Function to find the value of Mobius function// for all the numbers from 1 to nstatic void Mobius(){    for (int i = 1; i < N; i++)    {         // If number is one        if (i == 1)            mobius[i] = 1;        else        {             // If number has a squared prime factor            if (lpf[i / lpf[i]] == lpf[i])                mobius[i] = 0;             // Multiply -1 with the previous number            else                mobius[i] = -1 * mobius[i / lpf[i]];        }    }} // Function to find the number of pairs// such that gcd equals to 1static int gcd_pairs(int []a, int n){    // To store maximum number    int maxi = 0;     // To store frequency of each number    int []fre = new int[N];     // Find frequency and maximum number    for (int i = 0; i < n; i++)    {        fre[a[i]]++;        maxi = Math.Max(a[i], maxi);    }     least_prime_factor();    Mobius();     // To store number of pairs with gcd equals to 1    int ans = 0;     // Traverse through the all possible elements    for (int i = 1; i <= maxi; i++)    {        if (mobius[i] == 0)            continue;         int temp = 0;        for (int j = i; j <= maxi; j += i)            temp += fre[j];         ans += temp * (temp - 1) / 2 * mobius[i];    }     // Return the number of pairs    return ans;} // Driver codepublic static void Main (String[] args){    int []a = { 1, 2, 3, 4, 5, 6 };     int n = a.Length;     // Function call    Console.Write(gcd_pairs(a, n));}}     // This code is contributed by Rajput-Ji
<script> // Javascript program to find the number of pairs// such that gcd equals to 1   var N = 100050;     var lpf = Array(N).fill(0);    var mobius = Array(N).fill(0);     // Function to calculate least    // prime factor of each number    function least_prime_factor() {        for (i = 2; i < N; i++)             // If it is a prime number            if (lpf[i] == 0)                 for (j = i; j < N; j += i)                     // For all multiples which are not                    // visited yet.                    if (lpf[j] == 0)                        lpf[j] = i;    }     // Function to find the value of Mobius function    // for all the numbers from 1 to n    function Mobius() {        for (i = 1; i < N; i++) {             // If number is one            if (i == 1)                mobius[i] = 1;            else {                 // If number has a squared prime factor                if (lpf[i / lpf[i]] == lpf[i])                    mobius[i] = 0;                 // Multiply -1 with the previous number                else                    mobius[i] = -1 * mobius[i / lpf[i]];            }        }    }     // Function to find the number of pairs    // such that gcd equals to 1    function gcd_pairs(a , n) {        // To store maximum number        var maxi = 0;         // To store frequency of each number        var fre = Array(n+1).fill(0);         // Find frequency and maximum number        for (i = 0; i < n; i++) {            fre[a[i]]++;            maxi = Math.max(a[i], maxi);        }         least_prime_factor();        Mobius();         // To store number of pairs with gcd equals to 1        var ans = 0;         // Traverse through the all possible elements        for (i = 1; i <= maxi; i++) {            if (mobius[i] == 0)                continue;             var temp = 0;            for (j = i; j <= maxi; j += i)                temp = parseInt(temp+fre[j]);             ans += parseInt(temp * (temp - 1) / 2 * mobius[i]);        }         // Return the number of pairs        return ans;    }     // Driver code             var a = [ 1, 2, 3, 4, 5, 6 ];         var n = a.length;         // Function call        document.write(gcd_pairs(a, n)); // This code contributed by Rajput-Ji </script>
11
 
Time Complexity: O(N2)
Auxiliary Space: O(N)
mohit kumar 29
nidhi_biet
princiraj1992
Rajput-Ji
abdelrahmanyossef12
tapasrnk
subhamkumarm348
GCD-LCM
number-theory
Arrays
Mathematical
Arrays
number-theory
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7