Sum and product of k smallest and k largest composite numbers in the array | C ++ program to find the sum and product of k smallest and k largest composite numbers in an array ; Create a boolean vector " prime [ 0 . . n ] " . A value in prime [ i ] will finally be false if i is Not a prime , else true . ; If prime [ p ] is not changed , then it is a prime ; Update all multiples of p ; Function that calculates the sum and product of k smallest and k largest composite numbers in an array ; Find maximum value in the array ; Use sieve to find all prime numbers less than or equal to max_val ; Set 0 and 1 as primes so that they don 't get counted as   composite numbers ; Max Heap to store all the composite numbers ; Min Heap to store all the composite numbers ; Push all the composite numbers from the array to the heaps ; Calculate the products ; Calculate the sum ; Pop the current minimum element ; Pop the current maximum element ; Print results ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < bool > SieveOfEratosthenes ( int max_val ) { vector < bool > prime ( max_val + 1 , true ) ; for ( int p = 2 ; p * p <= max_val ; p ++ ) { if ( prime [ p ] == true ) { for ( int i = p * 2 ; i <= max_val ; i += p ) prime [ i ] = false ; } } return prime ; } void compositeSumAndProduct ( int arr [ ] , int n , int k ) { int max_val = * max_element ( arr , arr + n ) ; vector < bool > prime = SieveOfEratosthenes ( max_val ) ; prime [ 0 ] = true ; prime [ 1 ] = true ; priority_queue < int > maxHeap ; priority_queue < int , vector < int > , greater < int > > minHeap ; for ( int i = 0 ; i < n ; i ++ ) if ( ! prime [ arr [ i ] ] ) { minHeap . push ( arr [ i ] ) ; maxHeap . push ( arr [ i ] ) ; } long long int minProduct = 1 , maxProduct = 1 , minSum = 0 , maxSum = 0 ; while ( k -- ) { minProduct *= minHeap . top ( ) ; maxProduct *= maxHeap . top ( ) ; minSum += minHeap . top ( ) ; maxSum += maxHeap . top ( ) ; minHeap . pop ( ) ; maxHeap . pop ( ) ; } cout << " Sum ▁ of ▁ k - minimum ▁ composite ▁ numbers ▁ is ▁ " << minSum << " STRNEWLINE " ; cout << " Sum ▁ of ▁ k - maximum ▁ composite ▁ numbers ▁ is ▁ " << maxSum << " STRNEWLINE " ; cout << " Product ▁ of ▁ k - minimum ▁ composite ▁ numbers ▁ is ▁ " << minProduct << " STRNEWLINE " ; cout << " Product ▁ of ▁ k - maximum ▁ composite ▁ numbers ▁ is ▁ " << maxProduct ; } int main ( ) { int arr [ ] = { 4 , 2 , 12 , 13 , 5 , 19 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int k = 3 ; compositeSumAndProduct ( arr , n , k ) ; return 0 ; }