Count of subarrays having exactly K perfect square numbers | C # program to count of subarrays having exactly K perfect square numbers . ; A utility function to check if the number n is perfect square or not ; Find floating point value of square root of x . ; If square root is an integer ; Function to find number of subarrays with sum exactly equal to k ; Map to store number of subarrays starting from index zero having particular value of sum . ; To store the sum of element traverse so far ; Add current element to currsum ; If currsum = K , then a new subarray is found ; If currsum > K then find the no . of subarrays with sum currsum - K and exclude those subarrays ; Add currsum to count of different values of sum ; Return the final result ; Function to count the subarray with K perfect square numbers ; Update the array element ; If current element is perfect square then update the arr [ i ] to 1 ; Else change arr [ i ] to 0 ; Function call ; Driver Code ; Function call
using System ; using System . Collections ; using System . Collections . Generic ; class GFG { static bool isPerfectSquare ( double x ) { double sr = Math . Sqrt ( x ) ; return ( ( sr - Math . Floor ( sr ) ) == 0 ) ; } static int findSubarraySum ( int [ ] arr , int n , int K ) { Dictionary < int , int > prevSum = new Dictionary < int , int > ( ) ; int res = 0 ; int currsum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { currsum += arr [ i ] ; if ( currsum == K ) { res ++ ; } if ( prevSum . ContainsKey ( currsum - K ) ) res += ( prevSum [ currsum - K ] ) ; if ( prevSum . ContainsKey ( currsum ) ) { prevSum [ currsum ] ++ ; } else { prevSum [ currsum ] = 1 ; } } return res ; } static void countSubarray ( int [ ] arr , int n , int K ) { for ( int i = 0 ; i < n ; i ++ ) { if ( isPerfectSquare ( arr [ i ] ) ) { arr [ i ] = 1 ; } else { arr [ i ] = 0 ; } } Console . Write ( findSubarraySum ( arr , n , K ) ) ; } public static void Main ( string [ ] args ) { int [ ] arr = { 2 , 4 , 9 , 2 } ; int K = 2 ; int N = arr . Length ; countSubarray ( arr , N , K ) ; } }