Count of subarrays having exactly K prime numbers | A utility function to check if the number n is prime or not ; Base Cases ; Check to skip middle five numbers in below loop ; If n is divisible by i & i + 2 then it is not prime ; Function to find number of subarrays with sum exactly equal to k ; STL 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 primes ; Update the array element ; If current element is prime then update the arr [ i ] to 1 ; Else change arr [ i ] to 0 ; Function Call ; Driver Code ; Function Call
function isPrime ( n ) { let i ; if ( n <= 1 ) return false ; if ( n <= 3 ) return true ; if ( n % 2 == 0 n % 3 == 0 ) { return false ; } for ( i = 5 ; i * i <= n ; i += 6 ) { if ( n % i == 0 || n % ( i + 2 ) == 0 ) { return false ; } } return true ; } function findSubarraySum ( arr , n , K ) { let prevSum = new Map ( ) ; let res = 0 ; let currsum = 0 ; for ( let i = 0 ; i < n ; i ++ ) { currsum += arr [ i ] ; if ( currsum == K ) { res ++ ; } if ( prevSum . has ( currsum - K ) ) res += ( prevSum . get ( currsum - K ) ) ; if ( prevSum . has ( currsum ) ) { prevSum . set ( currsum , prevSum . get ( currsum ) + 1 ) } else { prevSum . set ( currsum , 1 ) } } return res ; } function countSubarray ( arr , n , K ) { for ( let i = 0 ; i < n ; i ++ ) { if ( isPrime ( arr [ i ] ) ) { arr [ i ] = 1 ; } else { arr [ i ] = 0 ; } } document . write ( findSubarraySum ( arr , n , K ) ) ; } let arr = [ 1 , 2 , 3 , 4 ] ; let K = 2 ; let N = arr . length ; countSubarray ( arr , N , K ) ;