Find N in the given matrix that follows a pattern | Function to return the row and the column of the given integer ; Binary search for the row number ; Condition to get the maximum x that satisfies the criteria ; Binary search for the column number ; Condition to get the maximum y that satisfies the criteria ; Get the row and the column number ; Return the pair ; Driver code
def solve ( n ) : NEW_LINE INDENT low = 1 NEW_LINE high = 10 ** 4 NEW_LINE x , p = n , 0 NEW_LINE while ( low <= high ) : NEW_LINE INDENT mid = ( low + high ) // 2 NEW_LINE sum = ( mid * ( mid + 1 ) ) // 2 NEW_LINE if ( x - sum >= 1 ) : NEW_LINE INDENT p = mid NEW_LINE low = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT high = mid - 1 NEW_LINE DEDENT DEDENT start , end , y , q = 1 , 10 ** 4 , 1 , 0 NEW_LINE while ( start <= end ) : NEW_LINE INDENT mid = ( start + end ) // 2 NEW_LINE sum = ( mid * ( mid + 1 ) ) // 2 NEW_LINE if ( y + sum <= n ) : NEW_LINE INDENT q = mid NEW_LINE start = mid + 1 NEW_LINE DEDENT else : NEW_LINE INDENT end = mid - 1 NEW_LINE DEDENT DEDENT x = x - ( p * ( p + 1 ) ) // 2 NEW_LINE y = y + ( q * ( q + 1 ) ) // 2 NEW_LINE r = x NEW_LINE c = q + 1 - n + y NEW_LINE return r , c NEW_LINE DEDENT n = 5 NEW_LINE r , c = solve ( n ) NEW_LINE print ( r , c ) NEW_LINE