Count of subsequences which consists exactly K prime numbers | Java implementation to find the count of subsequences which consist exactly K primes ; Returns factorial of n ; Function to return total number of combinations ; Function check whether a number is prime or not ; Corner case ; Check from 2 to n - 1 ; Function for finding number of subsequences which consists exactly K primes ; If number of primes are less thn k ; Driver code
import java . util . * ; class GFG { static int fact ( int n ) { int res = 1 ; for ( int i = 2 ; i <= n ; i ++ ) res = res * i ; return res ; } static int nCr ( int n , int r ) { return fact ( n ) / ( fact ( r ) * fact ( n - r ) ) ; } static boolean isPrime ( int n ) { if ( n <= 1 ) return false ; for ( int i = 2 ; i < n ; i ++ ) if ( n % i == 0 ) return false ; return true ; } static int countSubsequences ( int arr [ ] , int n , int k ) { int countPrime = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( isPrime ( arr [ i ] ) ) countPrime ++ ; } if ( countPrime < k ) return 0 ; return nCr ( countPrime , k ) * ( int ) Math . pow ( 2 , ( n - countPrime ) ) ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 } ; int K = 3 ; int n = arr . length ; System . out . println ( countSubsequences ( arr , n , K ) ) ; } }