Find a subarray of size K whose sum is a perfect square | Function to check if a given number is a perfect square or not ; Find square root of n ; Check if the square root is an integer or not ; Function to print the subarray whose sum is a perfect square ; Sum of first K elements ; If the first k elements have a sum as perfect square ; Iterate through the array ; If sum is perfect square ; If subarray not found ; Given array ; Given subarray size K ; Function Call
function isPerfectSquare ( n ) { var sr = Math . sqrt ( n ) ; return ( ( sr - Math . floor ( sr ) ) == 0 ) ; } function SubarrayHavingPerfectSquare ( arr , k ) { var ans = [ ] ; var sum = 0 , i ; for ( i = 0 ; i < k ; i ++ ) { sum += arr [ i ] ; } var found = false ; if ( isPerfectSquare ( sum ) ) { ans [ 0 ] = 0 ; ans [ 1 ] = i - 1 ; } else { for ( var j = i ; j < arr . length ; j ++ ) { sum = sum + arr [ j ] - arr [ j - k ] ; if ( isPerfectSquare ( sum ) ) { found = true ; ans [ 0 ] = j - k + 1 ; ans [ 1 ] = j ; } } for ( var k = ans [ 0 ] ; k <= ans [ 1 ] ; k ++ ) { document . write ( arr [ k ] + " " ) ; } } if ( found == false ) { document . write ( " " ) ; } } var arr = [ 20 , 34 , 51 , 10 , 99 , 87 , 23 , 45 ] ; var K = 3 ; SubarrayHavingPerfectSquare ( arr , K ) ;