Count subarrays with Prime sum | Function to count subarrays with Prime sum ; USE SIEVE TO FIND ALL PRIME NUMBERS LESS THAN OR EQUAL TO max_val Create a boolean array " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; Remaining part of SIEVE ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Initialize result ; Traverse through the array ; return answer ; Driver program
function primeSubarrays ( A , n ) { var max_val = parseInt ( Math . pow ( 10 , 7 ) ) ; var prime = new Array ( max_val + 1 ) ; prime . fill ( true ) ; prime [ 0 ] = false ; prime [ 1 ] = false ; for ( var p = 2 ; p * p <= max_val ; p ++ ) { if ( prime [ p ] == true ) { for ( var i = p * 2 ; i <= max_val ; i += p ) prime [ i ] = false ; } } var cnt = 0 ; for ( var i = 0 ; i < n - 1 ; ++ i ) { var val = A [ i ] ; for ( var j = i + 1 ; j < n ; ++ j ) { val += A [ j ] ; if ( prime [ val ] ) ++ cnt ; } } return cnt ; } var A = [ 1 , 2 , 3 , 4 , 5 ] ; var n = A . length ; document . write ( primeSubarrays ( A , n ) ) ;