Largest component size in a graph formed by connecting non |  ; mark this node as visited ; apply dfs and add nodes belonging to this component ; create graph and store in adjacency list form ; iterate over all pair of nodes ; if not co - prime ; build undirected graph ; visited array for dfs ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int dfs ( int u , vector < int > * adj , int vis [ ] ) { vis [ u ] = 1 ; int componentSize = 1 ; for ( auto it : adj [ u ] ) { if ( ! vis [ it ] ) { componentSize += dfs ( it , adj , vis ) ; } } return componentSize ; } int maximumComponentSize ( int a [ ] , int n ) { vector < int > adj [ n ] ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = i + 1 ; j < n ; j ++ ) { if ( __gcd ( a [ i ] , a [ j ] ) > 1 ) adj [ i ] . push_back ( j ) ; adj [ j ] . push_back ( i ) ; } } int answer = 0 ; int vis [ n ] ; for ( int k = 0 ; k < n ; k ++ ) { vis [ k ] = 0 ; } for ( int i = 0 ; i < n ; i ++ ) { if ( ! vis [ i ] ) { answer = max ( answer , dfs ( i , adj , vis ) ) ; } } return answer ; } int main ( ) { int n = 8 ; int A [ ] = { 2 , 3 , 6 , 7 , 4 , 12 , 21 , 39 } J2 : J6 ; cout << maximumComponentSize ( A , n ) ; return 0 ; }