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
function solve ( n ) { let low = 1 , high = 1e4 , x = n , p = 0 ; while ( low <= high ) { let mid = Math . floor ( ( low + high ) / 2 ) ; let sum = Math . floor ( ( mid * ( mid + 1 ) ) / 2 ) ; if ( x - sum >= 1 ) { p = mid ; low = mid + 1 ; } else { high = mid - 1 ; } } let start = 1 , end = 1e4 , y = 1 , q = 0 ; while ( start <= end ) { let mid = Math . floor ( ( start + end ) / 2 ) ; let sum = Math . floor ( ( mid * ( mid + 1 ) ) / 2 ) ; if ( y + sum <= n ) { q = mid ; start = mid + 1 ; } else { end = mid - 1 ; } } x = x - Math . floor ( ( p * ( p + 1 ) ) / 2 ) ; y = y + Math . floor ( ( q * ( q + 1 ) ) / 2 ) ; let r = x ; let c = q + 1 - n + y ; let ans = [ r , c ] ; return ans ; } let n = 5 ; let p = solve ( n ) ; document . write ( p [ 0 ] + " " + p [ 1 ] ) ;