Check if the sum of a subarray within a given range is a perfect square or not | Function to calculate the square root of the sum of a subarray in a given range ; Calculate the sum of array elements within a given range ; Finding the square root ; If a perfect square is found ; Reduce the search space if the value is greater than sum ; Reduce the search space if the value if smaller than sum ; Given Array ; Given range ; Function Call
function checkForPerfectSquare ( arr , i , j ) { let mid , sum = 0 ; for ( let m = i ; m <= j ; m ++ ) { sum += arr [ m ] ; } let low = 0 , high = parseInt ( sum / 2 ) ; while ( low <= high ) { mid = low + parseInt ( ( high - low ) / 2 ) ; if ( mid * mid == sum ) { return mid ; } else if ( mid * mid > sum ) { high = mid - 1 ; } else { low = mid + 1 ; } } return - 1 ; } let arr = [ 2 , 19 , 33 , 48 , 90 , 100 ] ; let L = 1 , R = 3 ; document . write ( checkForPerfectSquare ( arr , L , R ) ) ;