Find a subarray of size K whose sum is a perfect square | C ++ program for the above approach ; 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 ; Driver Code ; Given array ; Given subarray size K ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool isPerfectSquare ( int n ) { double sr = sqrt ( n ) ; return ( ( sr - floor ( sr ) ) == 0 ) ; } void SubarrayHavingPerfectSquare ( vector < int > arr , int k ) { pair < int , int > ans ; int sum = 0 , i ; for ( i = 0 ; i < k ; i ++ ) { sum += arr [ i ] ; } bool found = false ; if ( isPerfectSquare ( sum ) ) { ans . first = 0 ; ans . second = i - 1 ; } else { for ( int j = i ; j < arr . size ( ) ; j ++ ) { sum = sum + arr [ j ] - arr [ j - k ] ; if ( isPerfectSquare ( sum ) ) { found = true ; ans . first = j - k + 1 ; ans . second = j ; } } for ( int k = ans . first ; k <= ans . second ; k ++ ) { cout << arr [ k ] << " ▁ " ; } } if ( found == false ) { cout << " - 1" ; } } int main ( ) { vector < int > arr ; arr = { 20 , 34 , 51 , 10 , 99 , 87 , 23 , 45 } ; int K = 3 ; SubarrayHavingPerfectSquare ( arr , K ) ; return 0 ; }