Subarray of size K with prime sum | Generate all prime numbers in the range [ 1 , 1000000 ] ; Set all numbers as prime initially ; Mark 0 and 1 as non - prime ; If current element is prime ; Mark all its multiples as non - prime ; Function to print the subarray whose sum of elements is prime ; Store the current subarray of size K ; Calculate the sum of first K elements ; Check if currSum is prime ; Store the start and last index of subarray of size K ; Iterate over remaining array ; Check if currSum ; Driver Code
function sieve ( prime ) { for ( var i = 0 ; i < 1000000 ; i ++ ) { prime [ i ] = true ; } prime [ 0 ] = prime [ 1 ] = false ; for ( var i = 2 ; i * i <= 1000000 ; i ++ ) { if ( prime [ i ] ) { for ( var j = i * i ; j <= 1000000 ; j += i ) { prime [ j ] = false ; } } } } function subPrimeSum ( N , K , arr , prime ) { var currSum = 0 ; for ( var i = 0 ; i < K ; i ++ ) { currSum += arr [ i ] ; } if ( prime [ currSum ] ) { for ( var i = 0 ; i < K ; i ++ ) { document . write ( arr [ i ] + " " ) ; } return ; } var st = 1 , en = K ; while ( en < N ) { currSum += arr [ en ] - arr [ st - 1 ] ; if ( prime [ currSum ] ) { for ( var i = st ; i <= en ; i ++ ) { document . write ( arr [ i ] + " " ) ; } return ; } en ++ ; st ++ ; } } var arr = [ 20 , 7 , 5 , 4 , 3 , 11 , 99 , 87 , 23 , 45 ] var K = 4 ; var N = arr . length ; prime = Array ( 1000000 ) . fill ( 0 ) ; sieve ( prime ) ; subPrimeSum ( N , K , arr , prime ) ;