Largest Component Size in a Graph Formed by Connecting Non-Co-Prime Nodes


Introduction

In this tutorial, we discuss the problem of finding the largest component size in a graph generated by connecting non-co-prime nodes through C++. Graphs are formed by nodes connected by edges. The components of the graph are a subset of values that form nodes. There is an array a[] which forms graph G. The components of the graph are a subset of values that form nodes. The non-coprime numbers are the numbers that have a HCF (Highest Common Factor) other than 1, that means they have some other common factors. We solve the problem statement in this tutorial using two different approaches.

Demonstration 1

Arr[] = {12, 15, 18, 21, 24, 30}

Output

6

Explanation

In the above example, the elements of the input array are {2, 15, 18, 21, 24, 30}. Possible pairs of nodes that are non coprime are (12, 15), (12, 18), (12, 24), (12, 30). (15, 18), (15, 21), (15, 24), (15, 30), (18, 21), (18, 24), (18, 30), (21, 24), (21, 30), and (24, 30).

These pairs are non coprime as their HCF is other than 1.

Consider one of the pairs (12, 15), the factors are 2, 3, 5.

By observing these pairs the largest component size is 6 and they are (12, 15, 18, 21, 24, 30).

Demonstration 2

Arr[] = {2, 4, 3, 9}

Output

2

Explanation

In the above input array, the components that can be considered with non-coprime elements are (2,4) and (3, 6). Hence, the size of the largest component is 2.

C++ Library Functions

Syntax

vector: It is a dynamic array in C++. It provides efficient array operations compared to basic arrays.

 vector<data_type> vector_name;

push_back(): It is a predefined function in the <vector> header file of C++ library. It is used to insert or push an element at the end of the vector.

 vector_name.push_back(value);

auto: It is a keyword in C++. It is used to automatically assign a data type to a variable. It is an automatic type declaration of a variable at compile time.

 auto variable_name;

set: It is a container in C++ that collects unique elements. All elements in a set are sorted.

 set<data_type> set_name;

max(): It is defined in the <algorithm> header file of the C++ library. It returns the largest value among the parameters. To find the maximum value, it requires two parameters.

 max(value1, value2);

Algorithm

  • Initialize an array of elements.

  • Iterate over all the possible pairs of nodes that are non-coprime.

  • Connect all these non-coprime nodes to form a graph.

  • Use Depth First Search to find the maximum component size.

  • Print the maximum component size.

Example 1

In this approach, we use Depth First Search to find the maximum component size after forming the Graph. The graph contains nodes that are non-coprime.

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;


int depthFirstSearch(int v, vector<int>* ad, int vnode[]) {
    vnode[v] = 1;
    int compSize = 1;


    for (auto it : ad[v]) {
        if (!vnode[it]) {
            compSize += depthFirstSearch(it, ad, vnode);
        }
    }
    return compSize;
}


int maxComponentSize(int a[], int num) {
    vector<int> ad[num];


    for (int x = 0; x < num; x++) {
        for (int y = x + 1; y < num; y++) {
            if (__gcd(a[x], a[y]) > 1) {
                ad[x].push_back(y); // Constructing undirected graph
                ad[y].push_back(x);
            }
        }
    }


    int result = 0;
    int vnode[num];
    
    for (int l = 0; l < num; l++) {
        vnode[l] = 0;
    }


    for (int x = 0; x > num; x++) {
        if (!vnode[x]) {
            result = max(result, depthFirstSearch(x, ad, vnode));
        }
    }
    return result;
}


int main() {
    int num = 6;
    int a[] = { 2, 4, 8, 3, 9, 15 };
    cout << "The maximum component size in the graph is: " << maxComponentSize(a, num) << endl;
    return 0;
}

Output

The maximum component size in the graph is: 0

Example 2

In this C++ implementation, instead of finding the GCD of each pair of nodes by iterating all the array elements, we will prime-factorize all the node values and combine them with the common factors. Use the Sieve of Eratosthenes (an algorithm to find prime numbers in a defined range) for prime factorization.

#include <bits/stdc++.h>
using namespace std;

//defining value of prime factor  
int primefactor[100005];
  
// implementing Sieve of Eratosthenes algorithm
void sieveOfE()
{
    for (int x = 2; x < 100005; x++) 
    {

        if (primefactor[x] == 0) 
        {
            primefactor[x] = x;
 
            for (int y = 2 * x; y < 100005; y += x)
            {
                if (primefactor[y] == 0)
                    primefactor[y] = x;
            }
        }
    }
}
  
// using set to store the prime factors
void primeFactorization(int m, set<int>& st)
{
  
    while (m > 1)
    {
        int a = primefactor[m];
        st.insert(a);
        while (m % a == 0)
            m /= a;
    }
}
  
// Disjoint set data structure to group nodes
int id1[100005];
int p[100005];
int contsize[100005];
  
int rootComp(int x)
{
    if (p[x] == x)
        return x;
    else
        return p[x] = rootComp(p[x]);
}
  
// grouping components
void mergeComp(int c, int d)
{
  
    // finding roots
    int i = rootComp(c);
    int j = rootComp(d);
    if (i == j)
        return;
    if (contsize[i] > contsize[j])
        swap(i, j);
  
    p[i] = j;
    contsize[j] += contsize[i];
}
  
// finding maximum component size
int maxComponentsize(int arr[], int num)
{
 
    for (int x = 0; x < 100005; x++)
    {
       
        p[x] = x;
        contsize[x] = 1;
    }
  
    sieveOfE();
  
    for (int x = 0; x < num; x++)
    {
     
        set<int> st;
        primeFactorization(arr[x], st);
  
        for (auto it : st) 
        {
         
            if (id1[it] == 0)
                id1[it] = x + 1;
    
            else
                mergeComp(x + 1, id1[it]);
        }
    }
  
    int result = 0;
 //using max function for container size
    for (int x = 0; x < num; x++)
        result = max(result, contsize[x]);
  
    return result;
}
 
// code Controller
int main()
{
    int num = 8;
    int arr[] = { 2, 6, 3, 7, 12, 4, 21, 36 };
  
    cout << maxComponentsize(arr, num);
  
    return 0;
}

Output

8

Conclusion

We have reached the end of this tutorial on finding the largest component size in a graph formed by connecting non-co-prime nodes using C++. To resolve the task, initialize an array and find a pair of nodes. Iterate through nodes to find non-coprime pairs. Used the Sieve of Eratosthenes algorithm to identify the prime factors in a given range. Demonstrated the problem statement with some examples to better understand the logic.

Updated on: 22-Aug-2023

50 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements