Length of Longest Prime Subsequence in an Array | Python 3 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
N = 100005 NEW_LINE def SieveOfEratosthenes ( prime , p_size ) : NEW_LINE INDENT prime [ 0 ] = False NEW_LINE prime [ 1 ] = False NEW_LINE p = 2 NEW_LINE while p * p <= p_size : NEW_LINE INDENT if ( prime [ p ] ) : NEW_LINE INDENT for i in range ( p * 2 , p_size + 1 , p ) : NEW_LINE INDENT prime [ i ] = False NEW_LINE DEDENT DEDENT p += 1 NEW_LINE DEDENT DEDENT def longestPrimeSubsequence ( arr , n ) : NEW_LINE INDENT prime = [ True ] * ( N + 1 ) NEW_LINE SieveOfEratosthenes ( prime , N ) NEW_LINE answer = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if ( prime [ arr [ i ] ] ) : NEW_LINE INDENT answer += 1 NEW_LINE DEDENT DEDENT return answer NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 4 , 11 , 2 , 9 , 21 ] NEW_LINE n = len ( arr ) NEW_LINE print ( longestPrimeSubsequence ( arr , n ) ) NEW_LINE DEDENT