Product of every K ’ th prime number in an array | C ++ implementation of the approach ; Create a boolean array " prime [ 0 . . n ] " and initialize all the entries as true . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; 0 and 1 are not prime numbers ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; compute the answer ; count of primes ; product of the primes ; traverse the array ; if the number is a prime ; increase the count ; if it is the K 'th prime ; Driver code ; create the sieve
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define MAX  1000000 NEW_LINE bool prime [ MAX + 1 ] ; void SieveOfEratosthenes ( ) { memset ( prime , true , sizeof ( prime ) ) ; prime [ 1 ] = false ; prime [ 0 ] = false ; for ( int p = 2 ; p * p <= MAX ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= MAX ; i += p ) prime [ i ] = false ; } } } void productOfKthPrimes ( int arr [ ] , int n , int k ) { int c = 0 ; long long int product = 1 ; for ( int i = 0 ; i < n ; i ++ ) { if ( prime [ arr [ i ] ] ) { c ++ ; if ( c % k == 0 ) { product *= arr [ i ] ; c = 0 ; } } } cout << product << endl ; } int main ( ) { SieveOfEratosthenes ( ) ; int n = 5 , k = 2 ; int arr [ n ] = { 2 , 3 , 5 , 7 , 11 } ; productOfKthPrimes ( arr , n , k ) ; return 0 ; }