adding this to handle negative elements too .
int val = matrix [ i ] [ j ] ; if ( val < 0 ) { int res = k - ( abs ( val ) % k ) ; if ( res != mod ) { return -1 ; } } else { int foo = matrix [ i ] [ j ] ; if ( foo % k != mod ) { return -1 ; } } } }