Length of Longest Prime Subsequence in an Array | JavaScript program to find the length of Longest Prime Subsequence in an Array ; Function to create Sieve to check primes ; False here indicates that it is not prime ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p , set them to non - prime ; Function to find the longest subsequence which contain all prime numbers ; Precompute N primes ; Find the length of longest prime subsequence ; Driver code ; Function call
let N = 100005 function SieveOfEratosthenes ( prime , p_size ) { prime [ 0 ] = false ; prime [ 1 ] = false ; for ( let p = 2 ; p * p <= p_size ; p ++ ) { if ( prime [ p ] ) { for ( let i = p * 2 ; i <= p_size ; i += p ) prime [ i ] = false ; } } } function longestPrimeSubsequence ( arr , n ) { let prime = new Array ( N + 1 ) ; prime . fill ( true ) SieveOfEratosthenes ( prime , N ) ; let answer = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( prime [ arr [ i ] ] ) { answer ++ ; } } return answer ; } let arr = [ 3 , 4 , 11 , 2 , 9 , 21 ] ; let n = arr . length document . write ( longestPrimeSubsequence ( arr , n ) + " " ) ;