Length of Longest Prime Subsequence in an Array | C # 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
using System ; class GFG { static readonly int N = 100005 ; static void SieveOfEratosthenes ( bool [ ] prime , int p_size ) { prime [ 0 ] = false ; prime [ 1 ] = false ; for ( int p = 2 ; p * p <= p_size ; p ++ ) { if ( prime [ p ] ) { for ( int i = p * 2 ; i <= p_size ; i += p ) prime [ i ] = false ; } } } static int longestPrimeSubsequence ( int [ ] arr , int n ) { bool [ ] prime = new bool [ N + 1 ] ; for ( int i = 0 ; i < N + 1 ; i ++ ) prime [ i ] = true ; SieveOfEratosthenes ( prime , N ) ; int answer = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ arr [ i ] ] ) { answer ++ ; } } return answer ; } public static void Main ( String [ ] args ) { int [ ] arr = { 3 , 4 , 11 , 2 , 9 , 21 } ; int n = arr . Length ; Console . Write ( longestPrimeSubsequence ( arr , n ) + " STRNEWLINE " ) ; } }