Find N in the given matrix that follows a pattern | Java implementation of the approach ; 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
class GFG { static int [ ] solve ( int n ) { int low = 1 , high = ( int ) 1e4 , x = n , p = 0 ; while ( low <= high ) { int mid = ( low + high ) / 2 ; int sum = ( mid * ( mid + 1 ) ) / 2 ; if ( x - sum >= 1 ) { p = mid ; low = mid + 1 ; } else { high = mid - 1 ; } } int start = 1 , end = ( int ) 1e4 , y = 1 , q = 0 ; while ( start <= end ) { int mid = ( start + end ) / 2 ; int sum = ( mid * ( mid + 1 ) ) / 2 ; if ( y + sum <= n ) { q = mid ; start = mid + 1 ; } else { end = mid - 1 ; } } x = x - ( p * ( p + 1 ) ) / 2 ; y = y + ( q * ( q + 1 ) ) / 2 ; int r = x ; int c = q + 1 - n + y ; int ans [ ] = { r , c } ; return ans ; } public static void main ( String [ ] args ) { int n = 5 ; int [ ] p = solve ( n ) ; System . out . println ( p [ 0 ] + " ▁ " + p [ 1 ] ) ; } }