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

Given an array a of size N. The task is to find the number of pairs such that gcd(a[i], a[j]) 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), 3) 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 Mö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++

filter_none

edit
close

play_arrow

link
brightness_4
code

// 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 number
void 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 n
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 1
int 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 code
int 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;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find the number of pairs
// such that gcd equals to 1
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 number
static 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 n
static 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 1
static 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 code
public 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

chevron_right


Python3

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find the number of pairs
# such that gcd equals to 1
N = 100050
  
lpf = [0 for i in range(N)]
mobius = [0 for i in range(N)]
  
# Function to calculate least
# prime factor of each number
def 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 n
def 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 1
def 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 code
a = [1, 2, 3, 4, 5, 6]
  
n = len(a)
  
# Function call
print(gcd_pairs(a, n))
  
# This code is contributed by Mohit Kumar

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find the number of pairs
// such that gcd equals to 1
using 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 number
static 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 n
static 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 1
static 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 code
public 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

chevron_right


Output:

11


My Personal Notes arrow_drop_up

pawanasipugmailcom

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.