VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-the-size-of-the-largest-connected-gcd-component/

⇱ Find the size of the Largest connected GCD Component - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find the size of the Largest connected GCD Component

Last Updated : 23 Jul, 2025

Given an array arr of size N. Consider a graph formed using the given array where the graph has N vertices and the value of i'th vertices is arr[i] there is an edge between i'th and j'th vertice if gcd(arr[i], arr[j])>1. Your task is to print the size of the largest connected component formed with the above graph.

Examples:

Input: N=6, arr[]={10, 4, 2, 5, 3, 9}
Output: 4
Explanation: there are two components of 4, 2, largest is 4.

Input: N=10, arr[]={2, 10, 10, 1, 13, 8, 20, 2, 2, 16}
Output: 8
Explanation: there are eight components and the largest is 8.

Largest GCD Component using DSU:

  • Find the prime factors of every value.
  • Initialise n sets, each containing one vertex.
  • For every prime factor, we find if there is a set containing this prime factor. For this, we will make an array of 'PRIMEFACTORS’.
  • If there is no set containing ‘K’ as a prime factor, then ‘PRIMEFACTORS[K]’ is equal to -1.
  • Else, ‘PRIMEFACTORS[K]’ is equal to the set number that contains ‘K’ as a prime factor.
  • Iterate on the vertices, let ‘x’ denote the current vertex.
  • Iterate on the prime factors of ‘x’, let ‘K’ denote the current prime factor.
  • If 'PROMEFACTORS[K]’ is not equal to -1, then combine the set containing vertex ‘x’ and the set containing ‘K’ as a prime factor.
  • Return the maximum size

Below is the C++ implementation of the above approach:


Output
4

Time Complexity: O(N*sqrt(Arr[i])).
Auxiliary Space: O(N + max(Arr[i])).

Comment