Calculating GCD of each row and each column in O ( mn ) and store in arrays .
for ( let i = 0 ; i < n ; i ++ ) { for ( let j = 0 ; j < m ; j ++ ) { rgcd [ i ] = gcd ( rgcd [ i ] , mat [ i ] [ j ] ) ; cgcd [ j ] = gcd ( cgcd [ j ] , mat [ i ] [ j ] ) ; } }