Replace every matrix element with maximum of GCD of row or column | Python3 program to replace each each element with maximum of GCD of row or column . ; returning the greatest common divisor of two number ; Finding GCD of each row and column and replacing with each element with maximum of GCD of row or column . ; Calculating GCD of each row and each column in O ( mn ) and store in arrays . ; Replacing matrix element ; Driver Code
R = 3 NEW_LINE C = 4 NEW_LINE def gcd ( a , b ) : NEW_LINE INDENT if ( b == 0 ) : NEW_LINE INDENT return a NEW_LINE DEDENT return gcd ( b , a % b ) NEW_LINE DEDENT def replacematrix ( mat , n , m ) : NEW_LINE INDENT rgcd = [ 0 ] * R NEW_LINE cgcd = [ 0 ] * C NEW_LINE for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT rgcd [ i ] = gcd ( rgcd [ i ] , mat [ i ] [ j ] ) NEW_LINE cgcd [ j ] = gcd ( cgcd [ j ] , mat [ i ] [ j ] ) NEW_LINE DEDENT DEDENT for i in range ( n ) : NEW_LINE INDENT for j in range ( m ) : NEW_LINE INDENT mat [ i ] [ j ] = max ( rgcd [ i ] , cgcd [ j ] ) NEW_LINE DEDENT DEDENT DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT m = [ [ 1 , 2 , 3 , 3 ] , [ 4 , 5 , 6 , 6 ] , [ 7 , 8 , 9 , 9 ] ] NEW_LINE replacematrix ( m , R , C ) NEW_LINE for i in range ( R ) : NEW_LINE INDENT for j in range ( C ) : NEW_LINE INDENT print ( m [ i ] [ j ] , end = " ▁ " ) NEW_LINE DEDENT print ( ) NEW_LINE DEDENT DEDENT