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
from math import gcd NEW_LINE def dfs ( u , adj , vis ) : NEW_LINE INDENT vis [ u ] = 1 NEW_LINE componentSize = 1 NEW_LINE for x in adj [ u ] : NEW_LINE INDENT if ( vis [ x ] == 0 ) : NEW_LINE INDENT componentSize += dfs ( x , adj , vis ) NEW_LINE DEDENT DEDENT return componentSize NEW_LINE DEDENT def maximumComponentSize ( a , n ) : NEW_LINE INDENT adj = [ [ ] for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( i + 1 , n ) : NEW_LINE INDENT if ( gcd ( a [ i ] , a [ j ] ) > 1 ) : NEW_LINE INDENT adj [ i ] . append ( j ) NEW_LINE DEDENT adj [ j ] . append ( i ) NEW_LINE DEDENT DEDENT answer = 0 NEW_LINE vis = [ 0 for i in range ( n ) ] NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( vis [ i ] == False ) : NEW_LINE INDENT answer = max ( answer , dfs ( i , adj , vis ) ) NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT n = 8 NEW_LINE A = [ 2 , 3 , 6 , 7 , 4 , 12 , 21 , 39 ] NEW_LINE print ( maximumComponentSize ( A , n ) ) NEW_LINE DEDENT