Calculating GCD of each row and each column in O ( mn ) and store in arrays .
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