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
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define N  100005 NEW_LINE 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 ; } } } int longestPrimeSubsequence ( int arr [ ] , int n ) { bool prime [ N + 1 ] ; memset ( prime , true , sizeof ( prime ) ) ; SieveOfEratosthenes ( prime , N ) ; int answer = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ arr [ i ] ] ) { answer ++ ; } } return answer ; } int main ( ) { int arr [ ] = { 3 , 4 , 11 , 2 , 9 , 21 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << longestPrimeSubsequence ( arr , n ) << endl ; return 0 ; }